Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.