简体   繁体   中英

javascript jquery regexp replace

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

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

Try this:

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

This should work fine:

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

Hope this helps! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM