I am using lunr.js.
This Javascript code below:
var query = getUrlParameter('q');
var queryWithoutPlus = query.replace(/\+/g, " ");
searchField.value = queryWithoutPlus
index.search(queryWithoutPlus);
A query param string could look like test+ABCD+Test++Test2+-Test+-Test+Test
.
The code above replaces the + characters in the query parameter q
with spaces to display the result to the user in a nice manner,
Currently, a search string spaces
"test +test -test"
currently results in
"test test -test"
What I need is:
"test +test -test"
I tried to modify the resulting query multiple times using a tempQuery:
var tempQuery = query.replace(/\+\+/g, " -");
var queryWithoutPlus = tempQuery.replace(/\+\-/g, " -");
But this doesn't work out with the remaining + characters and doesn't feel correct.
Does it just boil down to using the correct regex (whatever it might be, advice welcome), or is there is even a better approach for using query parameters with lunr.js?
You need a negative lookbehind query (?<!\+)
"test+ABCD+Test++Test2+-Test+-Test+Test".replace(/(?<!\+)\+/g, " ")
>> "test ABCD Test +Test2 -Test -Test Test"
As noted, this is not available on some browsers, like Microsoft's. In that case you need to replace with a temporary expression
"test+ABCD+Test++Test2+-Test+-Test+Test".replace(/\+\+/g, "#spaceplus#")
.replace(/\+/g, " ").replace(/#spaceplus#/g, " +")
>> "test ABCD Test +Test2 -Test -Test Test"