9

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.

Richard77
  • 20,343
  • 46
  • 150
  • 252
  • possible duplicate of [Javascript multiple replace](http://stackoverflow.com/questions/832257/javascript-multiple-replace) –  Aug 07 '13 at 01:01
  • I repeatedly found that the default behavior of "replace" is almost useless and dangerous. Why would I want to replace the first occurrence only (in a general case) ? why not the second or third or last ? this method is a major bug creator because of it's very unexpected behavior. I would recommend creating a method with another name in String.prototype that uses the regex version suggested by Matt and start using it everywhere in your team. – Cesar Jan 30 '19 at 09:07

4 Answers4

27

Use a regex with the g flag.

var $id = id.replace(/\//g, '_');
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
10

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

var $id=id.split("/").join("_");
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
  • Both from a performance and clarity-of-intent perspective, I cannot see how this is ever preferable. – Matt Ball Aug 07 '13 at 01:04
  • 1
    @MattBall maybe when you have a dynamic separator and don't feel like escaping it to construct a RegExp object? – Fabrício Matté Aug 07 '13 at 01:07
  • 3
    @MattBall In most languages, using replace lets you replace a string with a string, instead of needing a regex every time. the subject.split(search).join(replacement) construct is the closest thing in JS to a normal string replace. It is absurd that you should be required to use a regex everytime you want to do string replacement in JS. – chiliNUT Aug 07 '13 at 01:09
2

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');
Joe Simmons
  • 1,828
  • 2
  • 12
  • 9
0
function strReplace( str ) {
if( typeof str === 'string' ) {
    return text.replace( /[\/]/g, function( match, pos, originalText ) {
        if( match === '/' ){
            return '_';
        }
    });
}
return '';
}

console.log( strReplace( /Admin/ListOfMovies ) );
Yuan Zhaohao
  • 574
  • 5
  • 4