gpt4 book ai didi

JavaScript 正则表达式 - 在字母之间添加 ~ 符号(空格后的字母除外)

转载 作者:行者123 更新时间:2023-12-02 01:27:51 24 4
gpt4 key购买 nike

除了空格后的第一个字母之外,如何在字母之间放置 ~ 符号?这是我通过到处尝试从这个网站得到的结果。

txt = text.split(/ +?/g).join(" ");
txt.replace(/(.)(?=.)/g, "$1~")

此正则表达式输出为

input = "hello friend"
output = "h~e~l~l~o~ ~f~r~i~e~n~d"

如何输出“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);

关于JavaScript 正则表达式 - 在字母之间添加 ~ 符号(空格后的字母除外),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74023297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com