简体   繁体   中英

Regular Expressions - Javascript - Single Quotes

Lets assume we have a couple variables. A. Str, a string, John's .... B. regex expression as shown below.

inner.Html DOES have John's in it.

What I dont get, is this code for regex never works when I have a str with a single quote in it. Any ideas?

var str = "John's"   
var regex = new RegExp("\>[^\<]+?(" + str  +")[^\>]+?\<", "gi");
var thismatch = regex.exec(this.innerHTML);

I am not sure about what your outer element looks like, but one main thing missing and the reason why your regex will not work when str has a single quote is because you need to escape the quote in the string.

var str = "John's".replace(/(\')/g, '\\$1'); // "John\'s";
var regex = new RegExp("\>[^\<]+?(" + str  +")[^\>]+?\<", "gi");
var thismatch = regex.exec(this.innerHTML);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM