I have following code to replace left spaces with a specific string but, It is not working as I want.
console.log(' asdadasdad as asdasd asasd'.replace(/^\s+/, 'x'))
It changed all left spaces with x, but It should change every left spaces with one x.
But I just need this output:
xxasdadasdad as asdasd asasd
How can I do it ? Thanks so much.
Use the String. replaceAll() method to replace all spaces in a string, e.g. str. replaceAll(' ', '-'); . The replaceAll method will return a new string where all occurrences of a space have been replaced by the provided replacement.
The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.
This will surely do in two lines:
var str =' asdadasdad as asdasd asasd';
console.log(str.trim().padStart(str.length, 'x'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With