I have following code to replace left spaces with a specific string but, It is not working as I want.
This will surely do in two lines:
var str =' asdadasdad as asdasd asasd';
console.log(str.trim().padStart(str.length, '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)
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'))