Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace all occurrences in a string [duplicate]

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?

like image 682
clarkk Avatar asked May 19 '11 21:05

clarkk


People also ask

How do you replace duplicates in a string in python?

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.

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

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.

How do you replace all occurrences of a string in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.


2 Answers

Use the global flag.

str.replace(/\n/g, '<br />'); 
like image 182
Brigham Avatar answered Sep 22 '22 05:09

Brigham


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

like image 30
Kerem Baydoğan Avatar answered Sep 19 '22 05:09

Kerem Baydoğan