[英]How can I replace a keyword but in HTML tags by JavaScript regular expression?
[英]Replace keyword with a javascript expression
我有一串像hey! <input/>, Welcome
hey! <input/>, Welcome
使用模板。
我需要用JS表达式this.input
替换每个<input/>
。
例如:
//Input
"hey! <input/>, Welcome";
Output should be:
"hey! " + this.input + ", Welcome";
我可以用" + this.input + "
替换字符串,但是问题是如果<input/>
在开头还是结尾怎么办?
处理此问题的最佳方法是什么?
编辑:
我不希望输出是字符串。 我希望输出是有效的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;
正如我在上面的评论中所写,您可以使用:
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);
编辑:
John Reisig发表了一篇博客文章,内容涉及使用javascript制作最小的模板语言解析器。 它写得很好,可能是您使用自己的模板语言的一个很好的起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.