2017-03-22 1 views
2

더 많은 일치 항목 중 n 번째 일치 항목을 바꿀 수있는 방법을 찾으려고합니다.일치하는 n 번째 일치 항목을 정규 표현식으로 바꿉니다

string = "one two three one one" 

는 어떻게 "하나"의 두 번째 선두로부터 목표는 무엇입니까?

이렇게 할 수 있습니까?

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

내가 노력하고 있습니다 jsfiddle을했던이

"one two three (one) one" 

같은 것을 얻을 수 있지만, 느낌이 좋지 않습니다. 코드 힙 (heaps of code)과 단순한 것에 혼란 스럽다.

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의 훌륭한 대안입니다. 내가 가장 잘 맞는 방법을 조사하겠습니다. –

관련 문제