2017-06-12 62 views
0

我寫了一個簡單的函數來替換一些字符串。使用替換javascript

規則:

  • 每個dot必須由改爲 「_attributes。」;
  • [numbers]必須替換爲.numbers; (numbers裝置1,123 ...等)

實際上我寫的替換這樣的:

str.replace(/(\[?\d*\]?\.)/g, '_attributes$1') 
    .replace(/\[(\d+)\]/g, '.$1'); 

輸入例子:

model.city 
model[0].city 
model0.city 
model[0].another_model[4].city 

預期輸出:

model_attributes.city 
model_attributes.0.city 
model0_attributes.city 
model_attributes.0.another_model_attributes.4.city 

它幾乎完成,但它失敗了,我有一個號碼(不帶括號)的情況下dot這樣前:

model0.city 

它打印:

model_attributes0.city 

雖然我希望它是:

model0_attributes.city 

下面是你玩,看到一個簡單的片斷我想要實現:

var fields = [ 
 
    'model.city', 
 
    'model[0].city', 
 
    'model0.city', 
 
    'model[0].another_model[4].city', 
 
    'model[0].another_model4.city' 
 
]; 
 

 
var expectedArr = [ 
 
    'model_attributes.city', 
 
    'model_attributes.0.city', 
 
    'model0_attributes.city', 
 
    'model_attributes.0.another_model_attributes.4.city', 
 
    'model_attributes.0.another_model4_attributes.city' 
 
]; 
 

 
var replacedArr = []; 
 
for (const field of fields) { 
 
    var replaced = field.replace(/(\[?\d*\]?\.)/g, '_attributes$1').replace(/\[(\d+)\]/g, '.$1'); 
 
    replacedArr.push(replaced); 
 
} 
 

 
console.log('expected => ', expectedArr); 
 
console.log('actual => ', replacedArr);

我有我的改變取代function,使工作? TIA。

回答

1

在第一個正則表達式,只是做一個羣集組可選,這樣

str.replace(/((?:\[\d+\])?\.)/g, '_attributes$1')

你很好走。

擴展

(       # (1 start) 
     (?: \[ \d+ \])?    # Optional '[ddd]' group 
     \.       # Required dot 
)        # (1 end) 

JS樣品

function PrintMod(str) 
 
{ 
 
    console.log(str.replace(/((?:\[\d+\])?\.)/g, '_attributes$1') 
 
     .replace(/\[(\d+)\]/g, '.$1')); 
 
} 
 

 
PrintMod('model.city'); 
 
PrintMod('model[0].city'); 
 
PrintMod('model0.city'); 
 
PrintMod('model[0].another_model[4].city'); 
 
PrintMod('model[0].another_model4.city');

1

這應該是你在找什麼:

var fields = [ 
 
    'model.city', 
 
    'model[0].city', 
 
    'model0.city', 
 
    'model[0].another_model[4].city', 
 
    'model[0].another_model4.city' 
 
]; 
 

 
var expectedArr = [ 
 
    'model_attributes.city', 
 
    'model_attributes.0.city', 
 
    'model0_attributes.city', 
 
    'model_attributes.0.another_model_attributes.4.city', 
 
    'model_attributes.0.another_model4_attributes.city' 
 
]; 
 

 
var replacedArr = []; 
 
for (const field of fields) { 
 
    var replaced = field.replace(/(\[\d+\])?\./g, '_attributes$1.').replace(/\[(\d+)\]/g, '.$1'); 
 
    replacedArr.push(replaced); 
 
} 
 

 
console.log('expected => ', expectedArr); 
 
console.log('actual => ', replacedArr);
.as-console-wrapper { max-height: 100% !important; top: 0; }