gpt4 book ai didi

javascript - 使用 JavaScript Regex 将字母替换为单词

转载 作者:行者123 更新时间:2023-11-30 12:40:10 24 4
gpt4 key购买 nike

我正在做一些需要语音表达的东西。目标是获取一个随机字符串——包含数字、字母和符号——并用单词替换字母。我遇到了一个问题。

它不想将第一个和最后一个字母更改为单词。这是因为表达式 /\sa\s/g(例如)搜索前面有空格的小写 a 的所有实例,信的背面。

假设您有一个随机字符串 h_OX%o2At

下面的代码返回 h _ OSCAR XRAY % oscar 2 ALPHA t,但我希望它返回 hotel _ OSCAR XRAY % oscar 2 ALPHA tango

代码如下:

phoneticExp.text(password.split("").join(" ").replace(/\sa\s/g, " alpha ").replace(/\sA\s/g, " ALPHA ").replace(/\sb\s/g, " bravo ").replace(/\sB\s/g, " BRAVO ").replace(/\sc\s/g, " charlie ").replace(/\sC\s/g, " CHARLIE ").replace(/\sd\s/g, " delta ").replace(/\sD\s/g, " DELTA ").replace(/\se\s/g, " echo ").replace(/\sE\s/g, " ECHO ").replace(/\sf\s/g, " foxtrot ").replace(/\sF\s/g, " FOXTROT ").replace(/\sg\s/g, " golf ").replace(/\sG\s/g, " GOLF ").replace(/\sh\s/g, " hotel ").replace(/\sH\s/g, " HOTEL ").replace(/\si\s/g, " india ").replace(/\sI\s/g, " INDIA ").replace(/\sj\s/g, " juliet ").replace(/\sJ\s/g, " JULIET ").replace(/\sk\s/g, " kilo ").replace(/\sK\s/g, " KILO ").replace(/\sl\s/g, " lima ").replace(/\sL\s/g, " LIMA ").replace(/\sm\s/g, " mike ").replace(/\sM\s/g, " MIKE ").replace(/\sn\s/g, " november ").replace(/\sN\s/g, " NOVEMBER ").replace(/\so\s/g, " oscar ").replace(/\sO\s/g, " OSCAR ").replace(/\sp\s/g, " papa ").replace(/\sP\s/g, " PAPA ").replace(/\sq\s/g, " quebec ").replace(/\sQ\s/g, " QUEBEC ").replace(/\sr\s/g, " romeo ").replace(/\sR\s/g, " ROMEO ").replace(/\ss\s/g, " sierra ").replace(/\sS\s/g, " SIERRA ").replace(/\st\s/g, " tango ").replace(/\sT\s/g, " TANGO ").replace(/\su\s/g, " uniform ").replace(/\sU\s/g, " UNIFORM ").replace(/\sv\s/g, " victor ").replace(/\sV\s/g, " VICTOR ").replace(/\sw\s/g, " wiskey ").replace(/\sW\s/g, " WISKEY ").replace(/\sx\s/g, " xray ").replace(/\sX\s/g, " XRAY ").replace(/\sy\s/g, " yankee ").replace(/\sz\s/g, " zulu ").replace(/\sZ\s/g, " ZULU "));

然后我尝试执行 /(\s|\s?)a(\s|\s?)/g 应该搜索小写的 a 前后都有一个空格或一个可选空格。那没有用。

我很迷茫。这是 Fiddle

最佳答案

与其查找被空格包围的字母,不如尝试查找单词边界。例如……

.replace(/\bh\b/g, "hotel")

Fiddle

关于javascript - 使用 JavaScript Regex 将字母替换为单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24773085/

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