Reputation: 199
Is there any way to remove the spaces just numbers in a string?
var str = "The store is 5 6 7 8"
after processing the output should be like this:
"The store is 5678"
How to do this?
Upvotes: 5
Views: 5751
Reputation: 28642
You can try following code snippet.
const regex = /(?!\d) +(?=\d)/g;
const str = `The store is 5 6 7 8`;
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
Upvotes: 2
Reputation: 1246
/([0-9]+) ([0-9]+)/
- removes space between digits.
But running s.replace replaces only first occurrences.
I put in into loop, so it keep deleting all spaces between two digits until there is no more spaces between digits.
prevS = '';
while(prevS !== s){
prevS = s; s = s.replace(/([0-9]+) ([0-9]+)/, '$1$2');
}
Upvotes: 1
Reputation: 10204
This is very close to santosh singh answer, but will not replace the space between is
and 5
.
const regex = /(\d)\s+(?=\d)/g;
const str = `The store is 5 6 7 8`;
const subst = `$1`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
https://regex101.com/r/nSZfQR/3/
Upvotes: 9
Reputation: 318
Hi You can try this.
var str = "The store is 5 6 7 8"
var regex = /(\d+)/g;
str.split(/[0-9]+/).join("") + str.match(regex).join('')
Hope this will work.
Upvotes: 0