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.
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.
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');
function strReplace( str ) {
if( typeof str === 'string' ) {
return text.replace( /[\/]/g, function( match, pos, originalText ) {
if( match === '/' ){
return '_';
}
});
}
return '';
}
console.log( strReplace( /Admin/ListOfMovies ) );