user759235
user759235

Reputation: 2207

regexp problem, the dot selects all text

I use some jquery to highlight search results. For some reason if i enter a basis dot, all of the text get selected. I use regex and replace to wrap the results in a tag to give the found matches a color.

the code that i use

 var pattern = new.RegExp('('+$.unique(text.split(" ")).join("|")+")","gi");

how can i prevent that the dot selects all text, so i want to leave the point out of the code(the dot has no power)

Upvotes: 0

Views: 545

Answers (5)

mVChr
mVChr

Reputation: 50185

This will replace all special RegExp characters (except for | since you're using that to join the terms) with their escaped version so you won't get unwanted matches or syntax errors:

var str = $.unique(text.split(" ")).join("|"),
    pattern;
str = str.replace(/[\\\.\+\*\?\^\$\[\]\(\)\{\}\/\'\#\:\!\=]/ig, "\\$&");
pattern = new RegExp('('+str+')', 'gi');

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237865

You need to escape the text you're putting into the regex, so that special characters don't have unwanted meanings. My code is based on some from phpjs.org:

var words = $.unique(text.split(" ")).join("|");
words = words.replace(/[.\\+*?\[\^\]$(){}=!<>|:\\-]/h, '\\$&'); // escape regex special chars

var pattern = new RegExp('(' + words + ")","gi");

This escapes the following characters: .\+*?[^]$(){}=!<>|:- with a backslash \ so you can safely insert them into your new RegExp construction.

Upvotes: 0

g.d.d.c
g.d.d.c

Reputation: 47988

You may be able to get there by doing this:

var pattern = new.RegExp('('+$.unique(text.replace('.', '\\.').split(" ")).join("|")+")","gi");

The idea here is that you're attempting to escape the period, which acts as a wild card in regex.

Upvotes: 1

Robert
Robert

Reputation: 21388

If you have a period in your RegExp it's supposed to match any character besides newline characters. If you don't want that functionality you need to escape the period.

Example RegExp with period escaped /word\./

Upvotes: 0

brymck
brymck

Reputation: 7663

The dot is supposed to match all text (almost everything, really). If you want to match a period, you can just escape it as \..

Upvotes: 0

Related Questions