正则表达式重复

时间:2015-10-14 21:37:50

标签: javascript regex

我试图添加' ig'在一个单词的每个音节的中间。例如,super(su和per)将成为sigupiger(sigu和piger)到目前为止,这是我的代码:

function iggify(text) {
    var iggEdText = text.split(/((a|e(?!$)|i(?!ng$)|o|u|y){1,3}|le$|ing$)/ig).join("ig");
    document.getElementById('resultField').innerHTML = iggEdText;
}

Demo codepen

加入后,我的正则表达重复了两次。例如单词变成了wigoigoigrds,而不仅仅是wigords。 我怎么能只重复一次呢?

1 个答案:

答案 0 :(得分:0)

您只需将ig附加到.replace()即可轻松实现的元音上,而不是分割加入:

text.replace(/(?:a|e(?!$)|i(?!ng$)|o|u|y){1,3}|le$|ing$/ig, "ig$&");
//            ^^^ - Non-capturing group                        ^^ - The whole matched text

我删除了外部捕获组并将第二个更改为非捕获组。由于我们用整个匹配替换,我在替换部分中使用$&反向引用(即我在替换期间恢复匹配的文本并在其之前添加ig)。

请参阅下面的整个代码段:



function iggify(text) {
    var iggEdText = text.replace(/(?:a|e(?!$)|i(?!ng$)|o|u|y){1,3}|le$|ing$/ig, "ig$&");
    document.getElementById('resultField').innerHTML = iggEdText;
}

<h1>
  Convert words to wig-ords!
</h1>
<div>
  <input id="inputBox" placeholder="Type words to iggify here">
</div>
<div>
  <button id="searchButton" onclick='iggify(document.getElementById("inputBox").value)'>Iggify!</button>
  <span id="resultField"></span>


</div>
</body>
&#13;
&#13;
&#13;