Replace all left spaces with a specific string

Viewed 113

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.

5 Answers

This will surely do in two lines:

  var str ='   asdadasdad as asdasd asasd';   
  console.log(str.trim().padStart(str.length, 'x')); 

You may use

.replace(/\s/gy, 'x')

Here, each whitespace that is at the start of the string is replaced with x. The combination of the g (global) and y (sticky) modifiers makes it match at the start of the string, and then consecutively until no match is found.

JS demo:

console.log(
  '  asdadasdad as asdasd asasd'.replace(/\s/gy, 'x')
)

You can use a callback function to generate the same length string which contains x.

console.log('  asdadasdad as asdasd asasd'.replace(/^\s+/, m => new Array(m.length).fill('x').join('')))


Or alternately with positive look-behind(not supported widely, check here).

    console.log('  asdadasdad as asdasd asasd'.replace(/(?<=^\s*)\s/g, 'x'))

You may use a lambda function as 2nd argument of .replace:

const s = '  asdadasdad as asdasd asasd';

var repl = s.replace(/^\s+/, m => m.replace(/\s/g, 'x'));

console.log(repl);

Currently you're replacing complete match with single x character but you need to repeat x to length of match,

let str = '  asdadasdad as asdasd asasd'
let replacedStr = str.replace(/^\s+/, (m) => 'x'.repeat(m.length))
console.log(replacedStr)

Related