Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
549 views
in Technique[技术] by (71.8m points)

javascript - Match dynamic string using regex

I'm trying to detect an occurrence of a string within string. But the code below always returns "null". Obviously something went wrong, but since I'm a newbie, I can't spot it. I'm expecting that the code returns "true" instead of "null"

var searchStr = 'width'; 
var strRegExPattern = '/'+searchStr+'/'; 
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please don't put '/' when you pass string in RegExp option

Following would be fine

var strRegExPattern = '\b'+searchStr+'\b'; 
"32:width: 900px;".match(new RegExp(strRegExPattern,'g'));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...