用特定的字符串替换所有左空格 [英] 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'))
它用x改变了所有左边的空格,但是应该用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 assasd asasd
我该怎么办?非常感谢.
How can I do it ? Thanks so much.
推荐答案
您可以使用
.replace(/\s/gy, 'x')
在这里,字符串开头的每个空格都被替换为 x
. g
(全局)和 y
(粘性)修饰符的组合使它在字符串的开头匹配,然后连续匹配直到找不到匹配项.
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演示:
console.log(
' asdadasdad as asdasd asasd'.replace(/\s/gy, 'x')
)
这篇关于用特定的字符串替换所有左空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文