-1

So I am working on something which has a search field to highlight matching strings/ characters from the data, to achieve this I am passing search query as regrex matching group. e.g.

var pattern = new RegExp( "("+ matchThis+")" );

And to eliminate special characters I tried this

var pattern = new RegExp( "[^.#&]("+ matchThis+")" );

but it doesn't work.

Any suggestions how to achieve above mentioned functionality, little explanation would help a lot as I am new to RegExp.

ikramf90
  • 92
  • 2
  • 17
  • What is `matchThis`? User-supplied or constant? ([mcve] please) – user202729 Oct 13 '18 at 08:37
  • A variable to store user supplied values – ikramf90 Oct 13 '18 at 08:40
  • Instead of trying to make the regex complex, just get all matching groups and filter out those with "special characters". – user202729 Oct 13 '18 at 08:43
  • Please, look at https://stackoverflow.com/questions/44604794/searching-for-words-in-string – svoychik Oct 13 '18 at 08:45
  • It highlights the matched text as soon as user enters a value. [ Think of it as find feature in your Chrome browser ] – ikramf90 Oct 13 '18 at 08:46
  • _"Think of it as find feature in your Chrome browser"_ - Which finds exactly what I'm typing without any special handling of "special characters" – Andreas Oct 13 '18 at 09:09
  • @user9804714: Can you give some sample text that should not get highlighted by your this statement? "And to eliminate special characters I tried this" – Pushpesh Kumar Rajwanshi Oct 13 '18 at 09:10
  • The question is extremely unclear. You should explain what you're trying to do, what `matchThis`'s contents is intended to be (you intend it to be raw text, not a regex), and how do you intend to use `pattern`, so someone may provide you a better solution. In the current state I can't see how your answer solves your problem. – user202729 Oct 13 '18 at 09:58

2 Answers2

0

Eventually I found a work around for above problem.

It will work perfectly fine if I remove all the special characters from users input searchThis variable in this case. It can be done using RegExp as

var pattern = new RegExp( "("+ searchThis.replace(/[^a-z0-9]/ig, "" ) +")" );

ikramf90
  • 92
  • 2
  • 17
0

The [^chars] construction does not eliminate special characters, it just won't accept them. So I think your answer is more in line with what you need. Keep in mind though that your line of code is not valid - the replace function call is not closed with a paren. Also it's not given a second argument, which might default to empty string, but for clearer code I would add it. I think it should be:

new RegExp( "(" + searchThis.replace(/[^a-z0-9]/ig, "") + ")" );
Casca
  • 61
  • 8