开发者

regexp problem, the dot selects all text

开发者 https://www.devze.com 2023-03-11 07:27 出处:网络
I use some jquery to high开发者_如何转开发light 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 f

I use some jquery to high开发者_如何转开发light 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)


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.


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');


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消