I have the following function which detects if there is 2 space and removes one:
filterText(text) {
if (text.indexOf(' ') >= 0) {
return text.replace(' ', ' ')
}
return text
}
is there a better way to achieve the same result?
If pattern is a string, only the first occurrence will be replaced.
You can either use String.prototype.replaceAll()
or try using RegEx with global flag.
The following example will remove 2 or more spaces with single space:
text = `some text, more text`;
text = text.replace(/\ +/g, ' ');
console.log(text);
If you want match exactly 2 space then:
text = text.replace(/\ {2}/g, ' ');