Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping Lucene Characters using Javascript Regex

I'm using elasticsearch in a NodeJS project, which is breaking upon entering one of the Lucene keywords into the search box. I'm looking for a simple implementation to escape their special characters. Is regex the best way? I've been fiddling with the regex for a bit now, and felt as if there were probably others that have already gone through this process.

like image 681
user2402831 Avatar asked Dec 01 '22 18:12

user2402831


1 Answers

Just needed to fiddle more.

var escaped = query.replace(/([\!\*\+\&\|\(\)\[\]\{\}\^\~\?\:\"])/g, "\\$1");    

Globally replace all instances of the chars lucene would yell about with their escaped version.

like image 114
user2402831 Avatar answered Dec 04 '22 06:12

user2402831