Forum Moderators: open

Message Too Old, No Replies

quotemeta for javascript regex?

need good algorithm to simulate \Q \E

         

amznVibe

6:57 am on Jul 1, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Unless my testing is wrong, javascript's regex functions don't seem to support \Q \E to make safe word wrapping quotes. I am using regex to search for something a user inputs, but I want to allow them to enter characters that my regex search is processing mistakenly.

Does anyone have a good js quotemeta [php.net] routine they are willing to share? Can't seem to find one out there.

amznVibe

7:49 am on Jul 1, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ah nevermind, my brain was just low on caffine. Worked this out, maybe it will help the next person who searches:

bs=String.fromCharCode(92);
unsafe=bs+".+*?[^]$(){}=!<>¦:";
for (i=0;i<unsafe.length;++i){
safesearch=safesearch.replace(unsafe.charAt(i),bs+unsafe.charAt(i));}

(where safesearch is the search terms you want to protect)

Bernard Marx

9:47 am on Jul 1, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I have a feeling that that will only replace the first instance of each of those characters in the string:

"only+first+instance" --> "only\+first+instance"

There is, no doubt, no regular expression usage that will do this at a stroke, without looping, but I don't know what it is.

Here's my amendment to your solution anyway.


bs=String.fromCharCode(92);
unsafe=bs+".+*?[^]$(){}=!<>¦:";
for (i=0;i<unsafe.length;++i){
safesearch=safesearch.replace(new RegExp("\\"+unsafe.charAt(i),"g"),bs+unsafe.charAt(i));
}

amznVibe

1:34 pm on Jul 1, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ah very good point, thank you.

I too figured there is a pure regex answer for this but it's giving me headaches thinking it out ;)