最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - build Regex string with js - Stack Overflow

programmeradmin1浏览0评论
<script>
var String = "1 Apple and 13 Oranges";
var regex = /[^\d]/g;
var regObj = new RegExp(regex);
document.write(String.replace(regObj,'')); 
</script>

And it works fine - return all the digits in the string.

However when I put quote marks around the regex like this:

var regex = "/[^\d]/g"; This doesn't work.

How can I turn a string to a working regex in this case?

Thanks

<script>
var String = "1 Apple and 13 Oranges";
var regex = /[^\d]/g;
var regObj = new RegExp(regex);
document.write(String.replace(regObj,'')); 
</script>

And it works fine - return all the digits in the string.

However when I put quote marks around the regex like this:

var regex = "/[^\d]/g"; This doesn't work.

How can I turn a string to a working regex in this case?

Thanks

Share Improve this question asked Nov 27, 2012 at 12:52 Bobbi XBobbi X 1971 silver badge9 bronze badges 2
  • 2 While BuddhiP's answer is correct in terms of what you asked, there's no need to do var regex = "/[^\\d]/g"; var regObj = new RegExp(regex); Just use the literal directly: var regObj = /[^\d]/g; That's what regex literals are for. – T.J. Crowder Commented Nov 27, 2012 at 12:57
  • 1 :) I did not say that you have to use both lines to construct a RegExp. Each code line in my answer constructs a full regular expression. @T.J.Crowder Thanks for clarification, may be I didn't make it clear enough. I agree with TJ that literal when ever possible. However, RegExp constructor gives you the ability to create dynamic regexps (i.e you can change them based on your variables, etc) – BuddhiP Commented Nov 27, 2012 at 14:29
Add a ment  | 

2 Answers 2

Reset to default 7

You can create regular expressions in two ways, using the regular expression literal notation, or RegExp constructor. It seems you have mixed up the two. :)

Here is the literal way:

var regex = /[^\d]/g;

In this case you don't have use quotes. / characters at the ends serve as the delimiters, and you specify the flags at the end.

Here is how to use the RegExp constructor, in which you pass the pattern and flags (optional) as string. When you use strings you have to escape any special characters inside it using a '\'.

Since the '\' (backslash) is a special character, you have to escape the backslash using another backslash if you use double quotes.

var regex = new RegExp("[^\\d]", "g");

Hope this makes sense.

As slash(\) has special meaning for strings (e.g. "\n","\t", etc...), you need to escape that simbol, when you are passing to regexp:

var regex = "[^\\d]";

Also expression flags (e.g. g,i,etc...) must be passed as separate parameter for RegExp. So overall:

var regex = "[^\\d]";
var flags = "g";
var regObj = new RegExp(regex, flags);
发布评论

评论列表(0)

  1. 暂无评论