Asked 7 years ago
21 Nov 2017
Views 1225
jassy

jassy posted

how to remove whitespace form string in javascript ?

how to remove white space form string in JavaScript ?

i know trim function

var r="I AM HELLO WORLD";
r.trim();


i want to remove space between word . so is that possible with trim function or we need new function for it which remove white space between word form string in JavaScript ?
ching

ching
answered Apr 24 '23 00:00

To remove whitespace from a string in JavaScript, you can use the replace () function with a regular expression. Here's an example of how to do this:



let myString = "   Hello, world!   ";
let trimmedString = myString.replace(/\s+/g, '');
console.log(trimmedString); // Output: "Hello,world!"

In the example above, the replace () function is called on the myString variable with a regular expression that matches one or more whitespace characters (\s+). The second argument to replace () is an empty string, which effectively removes all whitespace characters from the original string.

You can customize this code to remove whitespace in different ways, such as only removing leading or trailing whitespace. Additionally, you can modify the regular expression to remove only specific types of whitespace characters.
Post Answer