-3

I have a string with with quotes and spaces like' TEST 123 ' or " TEST 123 ". How can I remove spaces and quotes outside words and leave one space between words. Expected result: TEST 123

s_kamianiok
  • 462
  • 7
  • 24

2 Answers2

1

remove extra spaces in string javascript

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

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

bloo
  • 1,416
  • 2
  • 13
  • 19
1

You can use this regex,

^[ '"]+|[ '"]+$|( ){2,}

And replace it wit $1 where $1 captures a single space but of instance where there are two or more spaces.

Here, ^[ '"]+ matches any space or single or double quote one or more from start of string and similarly [ '"]+$ also matches any space or single or doublequote one or more at the end of string and gets replaced with empty string where as when ( ){2,} matches, which remains to be matched in the middle of string, gets replaced with a single space as captured in group1.

Regex Demo

Sample JS demo,

var arr = ["' TEST   123  '",'"  TEST  123  "'];

for (s of arr) {
 console.log(s + " --> " + s.replace(/^[ '"]+|[ '"]+$|( ){2,}/g,'$1'));
}
Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36