Xinyi Li
Xinyi Li

Reputation: 133

How do I remove all whitespaces except those between words with Regular Expression in Javascript

  var str=" hello world! , this is Cecy ";
  var r1=/^\s|\s$/g;
  console.log(str.match(r1));
  console.log(str.replace(r1,''))

Here, the output I expect is "hello world!,this is Cecy", which means remove whitespaces in the beginning and the end of the string, and the whitespace before and after the non-word characters. The output I have right now is"hello world! , this is Cecy", I don't know who to remove the whitespace before and after "," while keep whitespace between "o" and "w" (and between other word characters).

p.s. I feel I can use group here, but don't know who

Upvotes: 4

Views: 6664

Answers (4)

Zenoo
Zenoo

Reputation: 12880

You can use the RegEx ^\s|\s$|(?<=\B)\s|\s(?=\B)

  • ^\s handles the case of a space at the beginning

  • \s$ handles the case of a space at the end

  • (?<=\B)\s handles the case of a space after a non-word char

  • \s(?=\B) handles the case of a space before a non-word char

Demo.

EDIT : As ctwheels pointed out, \b is a zero-length assertion, therefore you don't need any lookbehind nor lookahead.

Here is a shorter, simpler version : ^\s|\s$|\B\s|\s\B

var str = " hello world! , this is Cecy ";
console.log(str.replace(/^\s|\s$|\B\s|\s\B/g, ''));

Upvotes: 4

ctwheels
ctwheels

Reputation: 22817

Method 1

See regex in use here

\B\s+|\s+\B
  • \B Matches a location where \b doesn't match
  • \s+ Matches one or more whitespace characters

const r = /\B\s+|\s+\B/g
const s = ` hello world! , this is Cecy `

console.log(s.replace(r, ''))


Method 2

See regex in use here.

(?!\b\s+\b)\s+
  • (?!\b +\b) Negative lookahead ensuring what follows doesn't match
    • \b Assert position as a word boundary
    • \s+ Match any whitespace character one or more times
    • \b Assert position as a word boundary
  • \s+ Match any whitespace character one or more times

const r = /(?!\b\s+\b)\s+/g
const s = ` hello world! , this is Cecy `

console.log(s.replace(r, ''))

Upvotes: 9

Mohsen Ghalbi
Mohsen Ghalbi

Reputation: 1

yuo can use the following command

str.replace(/ /g,'')

Upvotes: -2

Ricardo
Ricardo

Reputation: 2487

the method that your are looking for is trim() https://www.w3schools.com/Jsref/jsref_trim_string.asp

 var str = "       Hello World!       ";
console.log(str.trim())

Upvotes: 1

Related Questions