You can eliminate the white spaces within a JavaScript string by using the .replace()
method with the regular expression /s+/g
. Here is an example code:
let str = "Hello World! "
let newStr = str.replace(/\s+/g, "");
console.log(newStr); // output: "HelloWorld!"
In this example, the .replace()
method is used to find all the spaces in the str
string and replace them with an empty string ""
. The regular expression \s+
matches one or more white spaces, and the g
flag makes the regular expression global, meaning it will match all occurrences found in the string.
Asked: 2023-07-06 19:44:05 +0000
Seen: 9 times
Last updated: Jul 06 '23