To remove all whitespace characters from a string in JavaScript, you can use the `replace` method with a regular expression.
In this example,
str
with a value of "Hello World"
.replace
method with a regular expression /\s+/g
to replace all whitespace characters (including tabs, spaces, newlines, etc.) with an empty string in str
.str
to the console.let str = "Hello World";
let modifiedStr = str.replace(/\s+/g, "");
console.log("Modified string: " + modifiedStr);
Modified string: HelloWorld
In this example,
str
with a value of "apple\tbanana\n cherry "
.replace
method with a regular expression /\s+/g
to replace all whitespace characters (including tabs, spaces, newlines, etc.) with an empty string in str
.str
to the console.let str = "apple\tbanana\n cherry ";
let modifiedStr = str.replace(/\s+/g, "");
console.log("Modified string: " + modifiedStr);
Modified string: applebananacherry
In this tutorial, we learned How to Remove All Whitespace Characters from a String in JavaScript language with well detailed examples.