2016-11-22 8 views
1

特定の部分の文字列を分割して新しい値に置き換えようとしています。Reg Exを使用して文字列を分割して置換する

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

私は123.00/0 @および456.00/0 @ 456/0 @で123/0 @交換する必要が上記の文字列から。

最終出力:"split and replace @123.00/0 and test @456.00/1 and so on..."

文字列の@のval/n個があるかもしれないので、私はより多くの一般的な方法を探しています。私は文字列の特定の部分を置き換えることができません。

これは私が試したものです:

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 as parameter optionString#replaceにおける方法を提供することによって、コールバックを回避することができます。

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

考えるのOPを試してみてくださいすることは、これは私が全体のポイントは、置換値がハードコーディングされたことができないということであると考えている一般的なことする必要が言及します –

関連する問題