I want to replace all occurrences of white space characters (space, tab, newline) in JavaScript.
How to do so?
I tried:
str.replace(/ /gi, "X")
\s
is a meta character that covers all white space. You don't need to make it case-insensitive — white space doesn't have case.
str.replace(/\s/g, "X")
We can also use this if we want to change all multiple joined blank spaces with a single character:
str.replace(/\s+/g,'X');
Have you tried the \s
?
str.replace(/\s/g, "X");
Try this:
str.replace(/\s/gi, "X")
EDIT (correct version without typo):
str.replace(/\s/g, "X")
If you use
str.replace(/\s/g, "");
it replaces all whitespaces. For example:
var str = "hello my world";
str.replace(/\s/g, "") //the result will be "hellomyworld"
Actually it has been worked but
just try this.
take the value /\s/g into a string variable like
String a = /\s/g;
str = str.replaceAll(a,"X");
Not /gi but /g
var fname = "My Family File.jpg"
fname = fname.replace(/ /g,"_");
console.log(fname);
gives
"My_Family_File.jpg"
I've used the "slugify" method from underscore.string and it worked like a charm:
https://github.com/epeli/underscore.string#slugifystring--string
The cool thing is that you can really just import this method, don't need to import the entire library.
来源:https://stackoverflow.com/questions/6507056/replace-all-whitespace-characters