2017-03-22 5 views
2

これ以上の一致のn番目の一致を置き換える方法を見つけようとしています。私が「1」の第二の発生をターゲットにするにはどうすればよい一致のn番目の一致を正規表現に置き換えよう

string = "one two three one one" 

このようなことは可能ですか?

string.replace(/\bone\b/gi{2}, "(one)") 

この

"one two three (one) one" 

ような何かを得るために私が働いているjsfiddleをやったが、それは右に感じることはありません。コードのヒープと単純なことを混乱させる。

https://jsfiddle.net/Rickii/7u7pLqfd/

答えて

1

更新:

それ動的使用このようにするには:

((?:.*?one.*?){1}.*?)one 

値が1つの手段(N-1)。そのあなたのケースではn = 2

と置き換えることにより、次のとおりです。

$1\(one\) 

Regex101 Demo

const regex = /((?:.*?one.*?){1}.*?)one/m; 
 
const str = `one two three one one asdfasdf one asdfasdf sdf one`; 
 
const subst = `$1\(one\)`; 
 
const result = str.replace(regex, subst); 
 
console.log(result);

1

より一般的なアプローチは、代用の機能を使用することです。そのため

// Replace the n-th occurrence of "re" in "input" using "transform" 
 
function replaceNth(input, re, n, transform) { 
 
    let count = 0; 
 

 
    return input.replace(
 
    re, 
 
    match => n(++count) ? transform(match) : match); 
 
} 
 

 
console.log(replaceNth(
 
    "one two three one one", 
 
    /\bone\b/gi, 
 
    count => count ===2, 
 
    str => `(${str})` 
 
)); 
 

 
// Capitalize even-numbered words. 
 
console.log(replaceNth(
 
    "Now is the time", 
 
    /\w+/g, 
 
    count => !(count % 2), 
 
    str => str.toUpperCase()));

+0

ありがとう。それはRizwan M.Tumansの素晴らしい代替ソリューションです。どのアプローチが私に最も適しているかを調査します。 –

関連する問題