Cecil Theodore
Cecil Theodore

Reputation: 9949

Remove ALL white spaces from text

$("#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.

Upvotes: 836

Views: 1379421

Answers (13)

Balaji
Balaji

Reputation: 11017

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(' ',''));

Upvotes: 25

Asiful Islam Sakib
Asiful Islam Sakib

Reputation: 562

** 100% working

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

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

console.log(text) // I_love_you

Upvotes: 11

DSDmark
DSDmark

Reputation: 1271

Well, we can also use that [^A-Za-z] with g flag for removing all the spaces in text. Where negated or complemente or ^. Show to the every character or range of character which is inside the brackets. And the about g is indicating that we search globally.

let str = "D  S@ D2m4a   r k  23";

// We are only allowed the character in that range A-Za-z

str = str.replace(/[^A-Za-z]/g,"");  // output:- DSDmark

console.log(str)
javascript - Remove ALL white spaces from text - Stack Overflow

Upvotes: 1

Irfan wani
Irfan wani

Reputation: 5102

I don't understand why we need to use regex here when we can simply use replaceAll

let result = string.replaceAll(' ', '')

result will store string without spaces

Upvotes: 12

Basavaraj SK
Basavaraj SK

Reputation: 499

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

This will solve the problem.

Happy Coding !!!

Upvotes: 3

Adopted Idiots
Adopted Idiots

Reputation: 327

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

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

Upvotes: 0

Kartik Dolas
Kartik Dolas

Reputation: 761

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

Upvotes: 3

Jonathan Hall
Jonathan Hall

Reputation: 79794

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,'')

Upvotes: 1853

camillo777
camillo777

Reputation: 2377

Now you can use "replaceAll":

console.log(' a b    c d e   f g   '.replaceAll(' ',''));

will print:

abcdefg

But not working in every possible browser:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

Upvotes: 37

Daniel Rodrigues
Daniel Rodrigues

Reputation: 143

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

Example:

this.slug = removeAccent(this.slug).replace(/\s+/g,'');

Upvotes: -3

user9147812
user9147812

Reputation: 221

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

for example:

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

Upvotes: -2

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10396

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

Upvotes: 8

Pantelis
Pantelis

Reputation: 6146

.replace(/\s+/, "") 

Will replace the first whitespace only, this includes spaces, tabs and new lines.

To replace all whitespace in the string you need to use global mode

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

Upvotes: 365

Related Questions