Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all left spaces with a specific string

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.

like image 663
Jeremy Avatar asked Mar 29 '20 17:03

Jeremy


People also ask

How do you replace all spaces in a string?

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.

How do I replace multiple spaces in single space?

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.


1 Answers

This will surely do in two lines:

  var str ='   asdadasdad as asdasd asasd';   
  console.log(str.trim().padStart(str.length, 'x')); 
like image 99
nikhil sugandh Avatar answered Sep 30 '22 03:09

nikhil sugandh