[英]JavaScript Regex - add ~ symbol between lettes except letter after space
除了空格后的第一个字母外,如何在字母之间放置 ~ 符号? 这是我通过在这里和那里尝试从这个网站得到的。
txt = text.split(/ +?/g).join(" ");
txt.replace(/(.)(?=.)/g, "$1~")
这个正则表达式 output 作为
input = "hello friend"
output = "h~e~l~l~o~ ~f~r~i~e~n~d"
如何 output "h~e~l~l~o~ f~r~i~e~n~d"
?
使用\S
而不是.
匹配要在 - \S
旁边插入~
的字符时,匹配任何非空格字符,而.
匹配任何非换行符。
const text = 'hello friend'; const singleSpaced = text.split(/ +/g).join(" "); const output = singleSpaced.replace(/(\S)(?=.)/g, "$1~"); console.log(output);
或者
const text = 'hello friend'; const output = text.replace(/ +/g, ' ').replace(/(\S)(?=.)/g, "$1~"); console.log(output);
您可以使用此正则表达式通过replace
在一次操作中完成此操作:
(?<=\S)(?!$)
它与非空白字符(?<=\S)
之后的 position 匹配,但字符串末尾的 position (?!$)
。 然后您可以在这些位置插入一个~
:
text = "hello friend" txt = text.replace(/(?<=\S)(?,$)/g. '~') console.log(txt)
您可以匹配单个非空白字符,并断言右边不是可选的空白字符,后跟字符串的末尾。
在替换中使用完整匹配后跟波浪号$&~
\S(?!\s*$)
请参阅正则表达式演示。
input = "hello friend" output = input.replace(/\S(?,\s*$)/g. '$&~') console.log(output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.