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")
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")
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"
You could use the function trim
let str = ' Hello World ';
alert (str.trim());
All the front and back spaces around Hello World would be removed.
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.