2016-11-22 1 views
1

문자열의 특정 부분을 분할하여 새 값으로 바꾸려고합니다.Ex를 사용하여 문자열을 분할하고 바꿉니다.

예 : var _string = "split and replace @123/0 and test @456/1 and so on..." 내가 @ 123.00/0 123/0 @ 교체 할 필요가 위의 문자열에서

456/0 @ 456.00/0와 @.

최종 출력 : 문자열/@의 발 n 개의있을 수 있기 때문에 "split and replace @123.00/0 and test @456.00/1 and so on..."

나는 더 일반적인 방법을 검색하고 있습니다. 문자열의 특정 부분을 바꿀 수 없습니다.

이것은 내가 뭘하려 : 콜백 기능

var _string = "split and replace @123/0 and test @456/1 and so on..."; 
var regex = /\$[^\@]*\/0/g; 
var match = _string.match(regex); 

for(var i=0; i<match.length; i++){ 
    if(match[i].indexOf("@") > 0){ 
    // do replace of string... 
    } 
} 

답변

1

사용 String#replace 방법.

var _string = "split and replace @123/0 and test @456/1 and so on..."; 
 

 
console.log(
 
    _string.replace(/@(\d+)\/(\d)\b/g, function(_, m1, m2) { 
 
    return '@' + m1 + '.00/' + m2; 
 
    }) 
 
)


또는 당신은 String#replace 방법에 string as parameter option를 제공하여 콜백을 피할 수 있습니다.

var _string = "split and replace @123/0 and test @456/1 and so on..."; 
 

 
console.log(
 
    _string.replace(/@(\d+)\/(\d)\b/g, '@$1.00/$2') 
 
)

3

당신은 그룹이 캡처 혼자 올바른 정규식을 사용하여 replace()으로이 작업을 수행 할 수 있습니다. 이 시도 :

var _string = "split and replace @123/0 and test @456/1 and so on..."; 
 
_string = _string.replace(/(@\d{3})\/(\d)/g, "$1.00/$2"); 
 
console.log(_string);

-1
var _string = "split and replace @123/0 and test @456/1 and so on...".replace("@123/0", "@123.00/0").replace("@456/1", "@456.00/0"); 

+1

감안할 때 작전을 시도하면이 내가 요점은 대체 값이 하드 코딩 할 수 없다는 생각 제네릭 할 필요가 언급 –

관련 문제