2013-02-26 130 views
0

我需要一个字符串帮助器来替换方括号内的所有变量。使用javascript使用Regex将数组索引替换为数组元素。 Jquery

"Hello, [0]".modify(["ABC"]) 

"Heelo, [0], This is [1]".modify(["ABC", "XYZ"]) 

"Heelo, [0], This is [1], Your email address is [2]".modify(["ABC", "XYZ", "[email protected]"]) 

所以基本上修改()将采取阵列和替换适当的指数法的字符串。

任何建议都会有所帮助。

+2

http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format – 2013-02-26 12:01:06

+0

是的,我知道,如何在ruby中做到这一点。但我们怎么能在JavaScript中做到这一点? – 2013-02-26 12:01:37

+1

结帐这个http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery – 2013-02-26 12:01:57

回答

0

所有的答案都是有用的,

但我已经使用了在建造功能,从@PedrodelSol提供的链接

"Hello {0}, This is {1}".format(["ABC", "XYZ"]) 
0
String.prototype.modify = function(arr) { 
    return this.replace(/\[(\d+)\]/g, function(c, m) { 
     return arr[m] === undefined ? c : arr[m]; 
    }); 
}; 

"Heelo, [0], This is [1]".modify(["ABC", "XYZ"]); 
// "Heelo, ABC, This is XYZ" 
0
String.prototype.modify = function() { 
    var s = arguments[0]; 
    for (var i = 0; i < arguments.length - 1; i++) {  
    var reg = new RegExp("\\[" + i + "\\]", "gm");    
    s = s.replace(reg, arguments[i + 1]); 
    } 
    return s; 
}