admin管理员组文章数量:1287656
I'm stuck and have a really bad hangover. forgive me, I'd birthday yesterday. how can I split a string and replace the needed values by a simple, stupid javascript function (KISS)?
example:
var myvar = "John Doe needs %specialcharDD2% cookies a %specialcharXYV% !" // String
...
var result = "John Doe needs 50 cookies a day !" // result
any help is wele! :)
I'm stuck and have a really bad hangover. forgive me, I'd birthday yesterday. how can I split a string and replace the needed values by a simple, stupid javascript function (KISS)?
example:
var myvar = "John Doe needs %specialcharDD2% cookies a %specialcharXYV% !" // String
...
var result = "John Doe needs 50 cookies a day !" // result
any help is wele! :)
Share Improve this question edited Jul 13, 2011 at 12:37 mate64 asked Jul 13, 2011 at 12:24 mate64mate64 10.1k17 gold badges65 silver badges98 bronze badges 05 Answers
Reset to default 4don't know why you want to split up the string, but replace can be done simply like this:
myvar = myvar.replace("%specialchar1%",total)
myvar = myvar.replace("%specialchar2%",period);
http://www.w3schools./jsref/jsref_replace.asp
var txt = "John Doe needs %specialchar1% cookies a %specialchar2% !";
var replacements = [50, "day"];
txt.replace(/%specialchar\d+%/mg, function(findings) { return replacements[findings.match(/\d+/)[0] - 1] })
You could use the code below to loop through the matches within the string -
var text = 'John Doe needs %specialchar1% cookies a %specialchar2% !';
var matches = text.match(/%[a-zA-Z0-9]*%/g);
for (i=0; i<matches.length; i++) {
alert(matches[i]);
}
You might have to change the regex depending on what you're searching for. You can then substitute the 'alert' code with your desired functionality.
Alternatively;
result = repl(myvar, total, period);
function repl(input) {
for (var i = 1; i < arguments.length; i++)
input = input.replace("%specialchar" + i + "%", arguments[i]);
return input
}
//or for global; input = input.replace(new RegExp("%specialchar" + i + "%", "ig"), arguments[i]);
Update for token with any ending;
function repl(input) {
var i = 1, args = arguments;
return myvar.replace(/(%specialchar\w+%)/g, function() {
return args[i++];
});
}
MooTools has a substitute string extension
"Hello {myvariable}".substitute({myvariable: "world"});
MooTools docs
本文标签: jqueryjavascript split string and replace valuesStack Overflow
版权声明:本文标题:jquery - javascript: split string and replace values - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741316101a2371923.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论