0

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 work! Console outputs "missing /". Please, help me fix this.

Mike Partridge
  • 5,128
  • 8
  • 35
  • 47
DrStrangeLove
  • 11,227
  • 16
  • 59
  • 72

2 Answers2

2

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/

Chandu
  • 81,493
  • 19
  • 133
  • 134
2

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/

jfriend00
  • 683,504
  • 96
  • 985
  • 979