如何使用JQuery实现以下内容。jQuery String用不同变量替换重复的特殊字符
string = 'This $ should be greater than $ always'
。
,任何替换功能与不同的变量替换$
,说
replace(string, var1, var2)
。
如何使用JQuery实现以下内容。jQuery String用不同变量替换重复的特殊字符
string = 'This $ should be greater than $ always'
。
,任何替换功能与不同的变量替换$
,说
replace(string, var1, var2)
。
重新发明轮子是没有必要在这里我猜,但有一个jQuery插件,这里jQuery.validator.format()
var template = jQuery.validator.format("{0} is not a valid value");
// later, results in 'abc is not a valid value'
alert(template("abc"));
替换另一个字符$符号试试这样:
var s = "This is a string $ that contains $, a special character.";
s = s.replace(/\$/g, '*'); // use character instead of * according to you requirement.
我希望它能工作。这里是exmaple: - http://phpidiots.in/jquery/replace-special-character-with-another-character-using-jquery/
从我的理解,我相信你想要用不同的值替换$
。例如,如果Var1为val1
和VAR2是val2
你的原始字符串This $ should be greater than $ always
更换一次应该像This val1 should be greater than val2 always
只要在你的字符串$
符号的数量总是等于值的数量进行更换,这里是一个解。请注意,我正在使用一个数组来保存变量值。
信贷@Alnitak为replaceAt功能(参见this SO thread)
var string = 'This $ should be greater than $ always';
arr = ["val1", "val2"];
$.each(arr, function(k,v){
string = replaceAt(string,string.indexOf('$'), v);
});
$('#display').html(string);
// replace the 'n'th character of 's' with 't'
function replaceAt(s, n, t) {
return s.substring(0, n) + t + s.substring(n + 1);
}
这个怎么样http://jsfiddle.net/tq9et7bo/7/ –
你可能寻找内置['replace()'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter)函数,它具有'replacement'函数作为参数。 –
谢谢MKA,Simon为我工作。 –