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
  • 4,888
  • 8
  • 34
  • 46
DrStrangeLove
  • 10,539
  • 16
  • 57
  • 70

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
  • 78,650
  • 19
  • 129
  • 131
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
  • 637,040
  • 88
  • 896
  • 906