0

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?

3 Answers 3

7

Try a regexp with the global flag set:

var string = result.replace(/\r\n/g,'<br />');
Sign up to request clarification or add additional context in comments.

1 Comment

That's done it. I forget that you can regex replace in javascript
1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.