问题
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.
回答1:
This will surely do in two lines:
var str =' asdadasdad as asdasd asasd';
console.log(str.trim().padStart(str.length, 'x'));
回答2:
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);
回答3:
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'))
回答4:
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')
)
回答5:
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)
来源:https://stackoverflow.com/questions/60918361/replace-all-left-spaces-with-a-specific-string