簡體   English   中英

JavaScript 正則表達式 - 在空格后的字母之間添加 ~ 符號

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM