tags:

views:

262

answers:

3

I'm doing some string replacement on text I'm getting back from a JSON web service, the string may look like this:

"Hello I am a string.\r\nThis is a second line.\r\n\r\nThis is a bigger space"

I want to replace all the \r\n with <br /> tags so that the HTML is formatted, but when I do:

var string = result.replace('\r\n','<br />');

I only get the first instance replaced, not any other.

What am I doing wrong?

+7  A: 

Try a regexp with the global flag set:

var string = result.replace(/\r\n/g,'<br />');
Ates Goral
That's done it. I forget that you can regex replace in javascript
Slace
+1  A: 

Nothing. That's just how the JavaScript replace function works :)

You can use regular expressions to replace all occurences.

var string = result.replace(/\r\n/g, '<br />');

Take a look at this link

Aistina
A: 

While using a regular expression is most definitely what you want to use in this case, you may find yourself at least once or twice more arriving at this problem sometime in your life, and there's a slim chance you'll want to do a bit less than what a regular expression would naturally do. For this reason, I'll demonstrate an alternative method that, while accomplishing the same thing, leaves a bit more room for potential customization:

<script>
while (result.indexOf('\r\n') != -1)
 {
result = result.replace('\r\n', '<br />');
 }
string = result;
</script>

I like to use this method (a while block) and prototyping to modify the native replace() method attached to String objects in JavaScript.

Hexagon Theory