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 0
Add a ment  | 

5 Answers 5

Reset to default 4

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./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