Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace all occurrences of "/" in a string with "_" in JavaScript?

For some reason the "".replace() method only replaces the first occurrence and not the others. Any ideas?

like image 352
illuminatedtiger Avatar asked Jan 29 '10 01:01

illuminatedtiger


People also ask

How will you replace all occurrences of a string in JavaScript?

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 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 I change all occurence of 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 a certain part of a string JavaScript?

replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.


2 Answers

You have to use the g modifier (for global) in your replace call.

str = str.replace(/searchString/g, "replaceWith")

In your particular case it would be:

str = str.replace (/\//g, "_");

Note that you must escape the / in the regular expression.

like image 59
Cheryl Simon Avatar answered Oct 12 '22 22:10

Cheryl Simon


"Your/string".split("/").join("_")

if you don't require the power of RegExp

like image 34
meouw Avatar answered Oct 13 '22 00:10

meouw