Javascript - How to Remove All Extra Spacing Between Words

Javascript - How to remove all extra spacing between words

var string = "    This    should  become   something          else   too . ";
string = string.replace(/\s+/g, " ");

This code replaces a consecutive set of whitespace characters (\s+) by a single white space. Note that a white-space character also includes tab and newlines. Replace \s by a space if you only want to replace spaces.

If you also want to remove the whitespace at the beginning and end, include:

string = string.replace(/^\s+|\s+$/g, "");

This line removes all white-space characters at the beginning (^) and end ($). The g at the end of the RegExp means: global, ie match and replace all occurences.

How to remove the extra spaces in a string?

You're close.

Remember that replace replaces the found text with the second argument. So:

newString = string.replace(/\s+/g,''); // "thiscontainsspaces"

Finds any number of sequential spaces and removes them. Try replacing them with a single space instead!

newString = string.replace(/\s+/g,' ').trim();

Remove white space between the string using javascript

This should do the trick:

var str = "PB 10 CV 2662";
str = str.replace(/ +/g, "");

how to remove more than one space between two words of string in angular?

Use a regular expression to match two or more space characters, and replace with a single space:

const folderName = '    aaa         aaa';console.log(  folderName    .replace(/ {2,}/g, ' ')    .trim());

Remove ALL white spaces from text

You have to tell replace() to repeat the regex:

.replace(/ /g,'')

The g character makes it a "global" match, meaning it repeats the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.

If you want to match all whitespace, and not just the literal space character, use \s instead:

.replace(/\s/g,'')

You can also use .replaceAll if you're using a sufficiently recent version of JavaScript, but there's not really any reason to for your specific use case, since catching all whitespace requires a regex, and when using a regex with .replaceAll, it must be global, so you just end up with extra typing:

.replaceAll(/\s/g,'')

Remove everything except words and spaces between word

Add space character in your regex and then just .trim() it to format it nicely.