Ask Your Question
3

How can I eliminate the white spaces within a JavaScript string?

asked 2023-07-06 19:44:05 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-07-06 19:50:02 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-06 19:44:05 +0000

Seen: 8 times

Last updated: Jul 06 '23