I have a string with say: My Name is %NAME% and my age is %AGE%.
%XXX% are placeholders. We need to substitute values there from an object.
Object looks like: {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"}
I need to parse the object and replace the string with corresponding values. So that final output will be:
My Name is Mike and my age is 26.
The whole thing has to be done either using pure javascript or jquery.
The requirements of the original question clearly couldn’t benefit from string interpolation, as it seems like it’s a runtime processing of arbitrary replacement keys.
However, if you just had to do string interpolation, you can use:
Note the backticks delimiting the string, they are required.
For an answer suiting the particular OP’s requirement, you could use
String.prototype.replace()for the replacements.The following code will handle all matches and not touch ones without a replacement (so long as your replacement values are all strings, if not, see below).
jsFiddle.
If some of your replacements are not strings, be sure they exists in the object first. If you have a format like the example, i.e. wrapped in percentage signs, you can use the
inoperator to achieve this.jsFiddle.
However, if your format doesn’t have a special format, i.e. any string, and your replacements object doesn’t have a
nullprototype, useObject.prototype.hasOwnProperty(), unless you can guarantee that none of your potential replaced substrings will clash with property names on the prototype.jsFiddle.
Otherwise, if your replacement string was
'hasOwnProperty', you would get a resultant messed up string.jsFiddle.
As a side note, you should be called
replacementsanObject, not anArray.