Possible Duplicate:
Fastest method to replace all instances of a character in a string
How can you replace all occurrences found in a string?
If you want to replace all the newline characters (\n) in a string..
This will only replace the first occurrence of newline
str.replace(/\\n/, '<br />');
I cant figure out how to do the trick?
When it is required to replicate the duplicate occurrence in a string, the keys, the 'index' method and list comprehension can be used. The list comprehension is a shorthand to iterate through the list and perform operations on it.
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.
The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.
Use the global flag.
str.replace(/\n/g, '<br />');
Brighams answer uses literal regexp
.
Solution with a Regex object.
var regex = new RegExp('\n', 'g'); text = text.replace(regex, '<br />');
TRY IT HERE : JSFiddle Working Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With