I have a string like hey! <input/>, Welcome
hey! <input/>, Welcome
in a template.
I need to replace every <input/>
with the a JS expression this.input
.
eg:
//Input
"hey! <input/>, Welcome";
Output should be:
"hey! " + this.input + ", Welcome";
I can do a replace on the string with " + this.input + "
but the problem is what if <input/>
at the start or the end?
What is the best way to handle this?
Edit:
I don't want the output to be a string. I want the output to be a valid JS expression.
Valid inputs:
1) "hey! <input/>, Welcome";
2) "<input/>, Welcome";
3) "Welcome <input/>"
Outputs:
1) "hey! " + this.input + ", Welcome";
2) this.input + ", Welcome";
3) "Welcome " + this.input;
As I wrote in comments above you can use:
var input = 'foo';
var str = "hey! <input/>, Welcome";
str = str.replace(/(.*?)<input\/>(.*)/, '$1' + this.input + '$2');
console.log(str);
//=> "hey! foo, Welcome"
"hey! <input/>, Welcome".replace(/<input\/>/, this.input);
EDIT:
John Reisig made a blog entry about making a minimal templating language parser in javascript. It's well written and may be a good starting point for your own templating language.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.