Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all instances of character in javascript

Tags:

javascript

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?

like image 842
Niraj Choubey Avatar asked Apr 11 '11 10:04

Niraj Choubey


People also ask

How do you replace all occurrences of a character in a string in JavaScript?

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')

How do you replace all occurrences of a word in a string in JavaScript?

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.

How do you remove all instances of a character from a string in JavaScript?

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.

How do you replace letters in JavaScript?

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.


1 Answers

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.

like image 144
Kobi Avatar answered Oct 12 '22 13:10

Kobi