开发者

In JS, how do I determine if a string is contained within another string?

In Javascript, how do I determine if some specific HTML is contained within a larger hunk of HTML?

I tried regex:

var htmlstr;
var reg = /<b class="fl_r">Example</b>/.test(htmlstr);

but it doesn't wor开发者_开发技巧k! Console outputs "missing /". Please, help me fix this.


Regex is a bit of an overkill here. You can just use indexOf like this and not have to worry about escaping things in the string:

var htmlstr1 = 'foo';
var htmlstr2 = 'some stuff <b class="fl_r">Example</b> more stuff';

if (htmlstr1.indexOf('<b class="fl_r">Example</b>') != -1) {
    alert("found match in htmlstr1");
}

if (htmlstr2.indexOf('<b class="fl_r">Example</b>') != -1) {
    alert("found match in htmlstr2");
}

jsFiddle to play with it is here: http://jsfiddle.net/jfriend00/86Kny/


You need to escape the / character.

Try:

var htmlstr = '<b class="fl_r">Example</b>';
var reg =  /<b class="fl_r">Example<\/b>/.test(htmlstr);

Example @ http://jsfiddle.net/7cuKe/2/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜