[英]Replace keyword with a javascript expression
I have a string like hey! <input/>, Welcome
我有一串像hey! <input/>, Welcome
hey! <input/>, Welcome
in a template. hey! <input/>, Welcome
使用模板。
I need to replace every <input/>
with the a JS expression this.input
. 我需要用JS表达式this.input
替换每个<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? 我可以用" + this.input + "
替换字符串,但是问题是如果<input/>
在开头还是结尾怎么办?
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. 我希望输出是有效的JS表达式。
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. John Reisig发表了一篇博客文章,内容涉及使用javascript制作最小的模板语言解析器。 It's well written and may be a good starting point for your own templating language. 它写得很好,可能是您使用自己的模板语言的一个很好的起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.