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
Asked
Active
Viewed 1,425 times
-3

s_kamianiok
- 462
- 7
- 24
-
Please share with us what you've tried – j08691 Apr 22 '19 at 14:13
-
here is the logic for you, `trim`, `split`, `trim`, `join` – Void Spirit Apr 22 '19 at 14:13
2 Answers
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
-
-
single quotes...you basically replacing anything that fits the regular expression with a blank value – bloo Apr 22 '19 at 14:22
-
newString = string.replace(/[ '"]+/g, ' ').trim() - it leaves spaces before word – s_kamianiok Apr 22 '19 at 14:26
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.
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