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.
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')
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.
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.
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.
Use a regex with the g
flag.
var $id = id.replace(/\//g, '_');
I hate javascript replace since it always wants a regex. Try this
var $id=id.split("/").join("_");
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');
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