user3746998
user3746998

Reputation:

Find all words containing specific letters and special characters

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..

DEMO

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

Answers (2)

Mrchief
Mrchief

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

Federico C&#225;ceres
Federico C&#225;ceres

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

Related Questions