PDA

View Full Version : i use replace() but i want to know more, can anyone help?



smansakra
02-19-2009, 05:12 AM
i want to replace all "\n" caracters on mu string below by using replace(), but i think id doesn't enough.

look


var string = "hello... \n my name is reni \n i live at indonesia \n i 'm still a girl\n nice to meet you....";


my function is below


function replace_this(string){
string.replace('\n', '<br>');
return string;
}


but i the result is just return

hello... <br> my name is reni \n i live at indonesia \n i 'm still a girl\n nice to meet you....

i think just the first "\n" character that replaced not all character.

how to replace all "\n" character?

Twey
02-19-2009, 06:07 AM
If you use a string for the first parameter, only the first instance will be replaced. Instead, you probably want to use a regex, with the /g (global) flag set:


function nl2br(str) {
return str.replace(/\n/g, '<br>');
}

smansakra
02-19-2009, 06:19 AM
hi, it works thanks, hum, what is /g used for?

Twey
02-19-2009, 06:42 AM
This. It means 'match all occurrences'.

smansakra
02-19-2009, 06:45 AM
hum? i'm thinkking

jscheuer1
02-19-2009, 07:08 AM
See:

http://www.javascriptkit.com/jsref/regexp.shtml

Scroll down to the first table titled "Pattern flags (switches)".

smansakra
02-19-2009, 07:30 AM
aha, thank for the link, so i can read it:)