I have a string
var str= 'asdf<br>dfsdfs<br>dsfsdf<br>fsfs<br>dfsdf<br>fsdf';
I want to replace <br>
with \r
by using
str.replace(/<br>/g,'\r');
, but it is replacing only the first <br>
... Any idea why?
To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')
String.prototype.replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.
JavaScript String replace() The replace() method takes two parameters, the first of which is the character to be replaced and the second of which is the character to replace it with. This method replaces the first occurrence of the character. To remove the character, we could give the second parameter as empty.
You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global ( g ) modifier.
The code should work - with the /g
flag, it should replace all <br>
s. It's possible the problem is elsewhere.
Try this:
str = str.replace(/<br>/g, '\n');
'\n'
is probably more appropriate than \r
- it should be globally recognized as a newline, while \r
isn't common on its own. On Firefox, for example, \r
isn't rendered as a newline.
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