使用字符串替换将变量传递到正则表达式中 [英] Pass a variable into regex with string replace

查看:123
本文介绍了使用字符串替换将变量传递到正则表达式中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在字符串替换中有一个复杂的regEx,我想使用一个名为"tagname"的变量来代替单词Category,但是我不知道该怎么做.

I have a complicated regEx inside a string replace and I want to use a variable called "tagname" instead of the word Category, but I don't know how to do this.

$("textarea").val().replace(/\<Category\>(.*)\<\/Category\>/gi, "<Category>TextVariable</Category>");

我已经尝试过类似的操作,但是在第一个参数中却无效.

I have tried something like this, but it didn't work in the first parameter.

$("textarea").val().replace("/\<" + tagname + "\>(.*)\<\/" + tagname "\>/gi", "<" + tagname + ">" + TextVariable + "</" + tagname + ">");

推荐答案

使用RegExp构造函数代替正则表达式文字.

Use the RegExp constructor instead of regex literal.

var regex = new RegExp("<" + tagname + ">(.*)</" + tagname + ">", "gi");
$("textarea").val().replace(regex, "<" + tagname + ">" + 
   textVariable + "</" + tagname + ">");

您可以将其简化为:

//capture the tag name:
var regex = new RegExp("<(" + tagname + ")>(.*)</" + tagname + ">", "gi");
$("textarea").val().replace(regex, "<$1>" + textVariable + "</$1>");

但请记住,解析xml /html和regex是一个好主意

这篇关于使用字符串替换将变量传递到正则表达式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆