JavaScript Replace Characters in a String
To replace characters in a string in JavaScript, we can use the string.replace() methods,
Assign to a new variable
One thing to keep in mind is that the replace method does not change the
original string. So in order to get the new string after some of its
characters are replaced, we need to assign the operation to a new variable or
even itself.
var str = "a b c a b c";
str.replace("a","");
console.log(str);
//a b c a b c which is the same as before.
var newStr = str.replace("a","");
console.log(newStr);
//b c a b c. The first a is gone.
str = str.replace("a","");
console.log(str);
//b c a b c. Assign to itself wokks, too.
Differences between g and m in Regular Expression
Actually, you can just use g not gm in the regular expression if you want to replace multiple characters in a string. Here \n means a line break in the string.
var str = "a b c \na b c";
str = str.replace(/a/g,"");
console.log(str);
/*
b c
b c
*/
str = str.replace(/a/gm,"");
// or str = str.replace(/a/mg,"");
console.log(str);
/*
b c
b c
*/
Examples
Replacing all slashes
var str = "a/b/c/d"; str = str.replace(/\//g,""); console.log(str); // abcd
Replacing all backslashs
var str = "a\\b"; str = str.replace(/\\/g,""); console.log(str); // ab
Replacing all line breaks
var str = "a\nb\nc"; str = str.replace(/\n/g,""); console.log(str); // abc
Comments
Post a Comment