Reputation:
Suppose I have a list formed by words including special characters:
one
<two></two>
three#
$four
etc.
I want to find all words in the list that contain specific letters,
I've tried to use
var myList = "<one></one> $two three#";
var myRegex = /\bMYWORD[^\b]*?\b/gi;
alert(myList.match(myRegex));
But this does not work with special characters..
Unfortunately I'm new to javascript, and I don't know what is the best way to create the list
and to separe the words in the list..
Upvotes: 1
Views: 4043
Reputation: 76218
So based on your inputs, this does the trick:
var myList = "<one></one> $two three#";
var items = myList.split(' ');
$('#myInput').on('input',function(){
var matches = [];
for(var i = 0; i < items.length; i++) {
if(items[i].indexOf(this.value) > -1)
matches.push(items[i]);
}
$('#myDiv').text(matches.join(','));
});
Is this what you want?
Upvotes: 1
Reputation: 1216
If I understand correctly, all you need is to escape all special characters from your query string so that they are not considered as such by the RegEx engine. Something like this should work:
var myList = "<one></one> $two three#";
var query = "$two";
var myRegex = new RegEx(query.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"));
alert(myList.match(myRegex));
Hat tip to the answer that provided the escaping mechanism.
Is this what you needed?
PD: I'd also recommend using console
instead of alert.
Upvotes: 0