1

I'm trying to create a dynamic searchbar and i need help.

Right now im trying to replace a string with another string but i cant seem to succeed.

Im getting input from the user:

var location_keyword = $("#si_user_location").val();

Now i would like to replace a whitespace " " with a "|" to use this in my regexp as OR.

For example if the user wrote "Turkey Alanya", i want it to be "Turkey|Alanya" so that the search hits for both Turkey OR Alanya.

i tried something like this but it didnt work

var location_keyword = $("#si_user_location").val();
location_keyword.replace(" ","|");
var regexp_loc = new RegExp(location_keyword, "i");

i used to do this in PHP before with expressions such as:

preg_replace('/'.preg_quote($keyword).'/i', "<span>$0</span>", $string)

and i could replace strings caseinsensetive like this, how can i do this in js?

I used the last expression in PHP to highlight the keyword in the results, which i would like to do aswell in js.

hope i can get some help, thanks in advance! :)

best of regards, alexander

3 Answers 3

3

There are two problems with the use of replace on this line:

location_keyword.replace(" ","|");
  • It does not modify the string - it returns a new string. You need to reassign the result of the call to the original variable otherwise you won't see the changed string.
  • It only replaces the first occurrence unless you use a regular expression with the g (global) flag.

Try this instead:

location_keyword = location_keyword.replace(/ /g, '|');
Sign up to request clarification or add additional context in comments.

2 Comments

what is the /g in the regexp ?
/g stands for global, meaning replace all instances of the needle in haystack, instead of only replacing just the first instance you find.
1

Try this:

location_keyword  = location_keyword.replace(/\s+/,"|");

Comments

0

This should work fine:

location_keyword.replace(/ /g,"|");

Hope this helps! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.