167

I want to replace all occurrences of white space characters (space, tab, newline) in JavaScript.
How to do so?

I tried:

str.replace(/ /gi, "X")
Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
Sourav
  • 17,065
  • 35
  • 101
  • 159

10 Answers10

365

You want \s

Matches a single white space character, including space, tab, form feed, line feed.

Equivalent to

[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]

in Firefox and [ \f\n\r\t\v] in IE.


str = str.replace(/\s/g, "X");
Alex K.
  • 171,639
  • 30
  • 264
  • 288
45

We can also use this if we want to change all multiple joined blank spaces with a single character:

str.replace(/\s+/g,'X');

See it in action here: https://regex101.com/r/d9d53G/1

Explanation

/ \s+ / g

  • \s+ matches any whitespace character (equal to [\r\n\t\f\v ])
  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

  • Global pattern flags
    • g modifier: global. All matches (don't return after first match)
Travis J
  • 81,153
  • 41
  • 202
  • 273
Milos Stankovic
  • 471
  • 5
  • 7
  • The regex plus (+) is useful for my use case where I'm replacing whitespace type characters with an underscore (_) and if my users fat finger an extra space I really don't want to display an extra _. Thanks for this! – John Dec 07 '21 at 19:20
38

\s is a meta character that covers all white space. You don't need to make it case-insensitive — white space doesn't have case.

str.replace(/\s/g, "X")
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
8

Have you tried the \s?

str.replace(/\s/g, "X");
Headshota
  • 21,021
  • 11
  • 61
  • 82
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
7

If you use

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

it replaces all whitespaces. For example:

var str = "hello my world";
str.replace(/\s/g, "") //the result will be "hellomyworld"
GigiProve
  • 337
  • 1
  • 5
  • 15
5

Try this:

str.replace(/\s/g, "X")
VoteCoffee
  • 4,692
  • 1
  • 41
  • 44
Headshota
  • 21,021
  • 11
  • 61
  • 82
3

Not /gi but /g

var fname = "My Family File.jpg"
fname = fname.replace(/ /g,"_");
console.log(fname);

gives

"My_Family_File.jpg"
Dimitrios Ververidis
  • 1,118
  • 1
  • 9
  • 33
1

You could use the function trim

let str = ' Hello World ';

alert (str.trim());

All the front and back spaces around Hello World would be removed.

Vickel
  • 7,879
  • 6
  • 35
  • 56
Anseam
  • 19
  • 1
1

Actually it has been worked but

just try this.

take the value /\s/g into a string variable like

String a = /\s/g;

str = str.replaceAll(a,"X");
Siten
  • 4,515
  • 9
  • 39
  • 64
0

I've used the "slugify" method from underscore.string and it worked like a charm:

https://github.com/epeli/underscore.string#slugifystring--string

The cool thing is that you can really just import this method, don't need to import the entire library.

dude
  • 5,678
  • 11
  • 54
  • 81