Remove ALL white spaces from text

Viewed 1142814
$("#topNav" + $("#breadCrumb2nd").text().replace(" ", "")).addClass("current");

This is a snippet from my code. I want to add a class to an ID after getting another ID's text property. The problem with this, is the ID holding the text I need, contains gaps between the letters.

I would like the white spaces removed. I have tried TRIM()and REPLACE() but this only partially works. The REPLACE() only removes the 1st space.

11 Answers

Regex for remove white space

\s+

var str = "Visit Microsoft!";
var res = str.replace(/\s+/g, "");
console.log(res);

or

[ ]+

var str = "Visit Microsoft!";
var res = str.replace(/[ ]+/g, "");
console.log(res);

Remove all white space at begin of string

^[ ]+

var str = "    Visit Microsoft!";
var res = str.replace(/^[ ]+/g, "");
console.log(res);

remove all white space at end of string

[ ]+$

var str = "Visit Microsoft!      ";
var res = str.replace(/[ ]+$/g, "");
console.log(res);

    var mystring="fg gg";
   console.log(mystring.replaceAll(' ',''))

** 100% working

use replace(/ +/g,'_'):

let text = "I     love you"
text = text.replace( / +/g, '_') // replace with underscore ('_')

console.log(text) // I_love_you

Using String.prototype.replace with regex, as mentioned in the other answers, is certainly the best solution.

But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split and String.prototype.join:

const text = ' a b    c d e   f g   ';
const newText = text.split(/\s/).join('');

console.log(newText); // prints abcdefg

let str = 'a big fat hen clock mouse '
console.log(str.split(' ').join(''))
// abigfathenclockmouse

simple solution could be : just replace white space ask key value

val = val.replace(' ', '')

Use replace(/\s+/g,''),

for example:

const stripped = '    My String With A    Lot Whitespace  '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'

Using .replace(/\s+/g,'') works fine;

Example:

this.slug = removeAccent(this.slug).replace(/\s+/g,'');
function RemoveAllSpaces(ToRemove)
{
    let str = new String(ToRemove);
    while(str.includes(" "))
    {
        str = str.replace(" ", "");
    }
    return str;
}
Related