我正在做一些需要语音表达的东西。目标是采用随机字符串 - 包含数字,字母和符号 - 并用字替换字母。我遇到了一个问题。
它不想将第一个和最后一个字母更改为单词。这是因为表达式/\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
答案 0 :(得分:2)
答案 1 :(得分:1)
您还需要在字符串的开头和结尾搜索锚点。对于每个角色,您需要执行以下操作:/(\s|^)a(\a|$)/g
。我可能也会创建一个开始/结束字符的哈希并循环,所以你不需要在五十个地方进行这些更改!
我在这里对h和t进行了相关更改,例如:http://jsfiddle.net/HGrV8/
答案 2 :(得分:0)
为什么不避免正则表达式而是做这样的事情。
的Javascript
var lookup = {
a: 'alpha',
b: 'bravo',
c: 'charlie',
d: 'delta',
e: 'echo',
f: 'foxtrot',
g: 'golf',
h: 'hotel',
i: 'india',
j: 'juliet',
k: 'kilo',
l: 'lima',
m: 'mike',
n: 'november',
o: 'oscar',
p: 'papa',
q: 'quebec',
r: 'romeo',
s: 'siera',
t: 'tango',
u: 'uniform',
v: 'victor',
w: 'wiskey',
x: 'xray',
y: 'yankee',
z: 'zulu',
};
function toPhonetic(text) {
return text.split('').map(function (character) {
var lower = character.toLowerCase(),
word;
if (lookup.hasOwnProperty(lower)) {
word = lookup[lower];
if (character === lower) {
return word;
}
return word.toUpperCase();
}
return character;
}).join(' ');
}
var password = $("#password").text(),
phoneticExp = $("#phonetic");
phoneticExp.text(toPhonetic(password));
上