1

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

Mrchief
  • 75,126
  • 20
  • 142
  • 189
  • Which specific letters are you trying to match? – Evan Davis Sep 02 '14 at 17:30
  • I'd like to match any letter or character if possible.. –  Sep 02 '14 at 17:31
  • 1
    Are you just trying to get that list into an array? Why not just `split` the text on linebreak? – Evan Davis Sep 02 '14 at 17:32
  • What end-result do you actually want? What should the output of this function/approach be, given that input? – David Thomas Sep 02 '14 at 17:34
  • @DavidThomas the end result i want is use a text input to choose the value to match, and be able to match word that incude special characters –  Sep 02 '14 at 17:37
  • You need to improvise this question. It is very unclear as to what you actually want. E.g., if I type in "one" what should I see? `/`? – Mrchief Sep 02 '14 at 18:16
  • @Mrchief yes, if I type "one" I want to match "" –  Sep 02 '14 at 18:20
  • So in that case, you need to split the list and run individual matches, hang on, will post a fiddle soon. – Mrchief Sep 02 '14 at 18:22
  • @Mrchief Thank you, any help is really much appreciated, I will accept your answer :) –  Sep 02 '14 at 18:35

2 Answers2

1

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?

Mrchief
  • 75,126
  • 20
  • 142
  • 189
0

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.

Community
  • 1
  • 1
Federico Cáceres
  • 1,216
  • 12
  • 19