Reputation: 1374
I have following text in a table td (8" & 12")
My code is
var match = $('#table_body > tr > td:contains("' + searchterm + '")');
when I try to find (8" & 12") this getting following error
Error: Syntax error, unrecognized expression: :contains("")"
the last ") two characters are creating problem what it the solution I tried escape string (adding slashes) error is gone but no search result with this
Upvotes: 2
Views: 700
Reputation: 92274
It works if you use single quotes surrounding your td:contains('some text with "quotes"')
. The documentation does not list using double quotes as a valid alternative. Note that you don't really need the surrounding quotes, you can just use bare words. It will work whether your text contains single or double quotes.
var match = $("#table_body > tr > td:contains('" +searchterm+ "')");
// or without quotes altogether
var match = $("#table_body > tr > td:contains(" +searchterm+ ")");
Example:
var text = '8" 12"';
var text2 = '5" 6"'
var text3 = '2\' 4"';
var text4 = "Testing (1' 3')";
// Quotes are allowed
$("div:contains('"+text+"')").css('background-color', 'red');
// But not necessary
$("div:contains("+text2+")").css('background-color', 'yellow');
// Works with mixed single and double quotes
$("div:contains("+text3+")").css('background-color', 'gray');
// However, it doesn't support parentheses, you'll have to search it yourself
// And make sure you escape regex special characters
// Escapes any special characters
RegExp.escape = function(s, flags) {
return new RegExp(s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), flags);
};
console.log(RegExp.escape("1' 3')"))
$('div').filter(function(i, el) {
return $(el).text().match(RegExp.escape("1' 3')"));
}).css('background-color', '#fef0e4');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>8" 12"</div>
<div>5" 6"</div>
<div>2' 4"</div>
<div>1' 3')</div>
Upvotes: 1