javascript: split string and replace values
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开发者_StackOverflow中文版 a %specialcharXYV% !" // String
...
var result = "John Doe needs 50 cookies a day !" // result
any help is welcome! :)
don'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.com/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
精彩评论