Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript replace() is not replacing all the characters match

Tags:

javascript

I want to turn /Admin/ListOfMovies into _Admin_ListOfMovies using replace().

var $id = id.replace('/', '_');

It looks like it only replacing the first /. How do I replace all of them?

Thanks for helping.

like image 445
Richard77 Avatar asked Aug 07 '13 00:08

Richard77


People also ask

Does replace replace all occurrences?

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 character in a string in JavaScript?

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.

How do I replace multiple characters in a string?

If you want to replace multiple characters you can call the String. prototype. replace() with the replacement argument being a function that gets called for each match. All you need is an object representing the character mapping which you will use in that function.

How do I replace all characters?

Use the replace() method to replace umlaut characters in JavaScript. The first parameter the method takes is the character you want to replace, and the second - the replacement string. The method returns a new string where the matches are replaced.


3 Answers

Use a regex with the g flag.

var $id = id.replace(/\//g, '_');
like image 52
Matt Ball Avatar answered Oct 20 '22 19:10

Matt Ball


I hate javascript replace since it always wants a regex. Try this

var $id=id.split("/").join("_");
like image 42
chiliNUT Avatar answered Oct 20 '22 18:10

chiliNUT


If you don't want to use the global flag which will do the replace function twice on your string, you can do this method which is a bit more specific and only replaces it once; it's also useful to know for other situations.

var $id = id.replace(/\/(\w+)\/(\w+)/, '_$1_$2');
like image 42
Joe Simmons Avatar answered Oct 20 '22 19:10

Joe Simmons