javascript javascript regexp替换 [英] javascript jquery regexp replace
问题描述
我正在尝试创建动态搜索栏,我需要帮助.
现在我正尝试用另一个字符串替换一个字符串,但我似乎无法成功.
我正在从用户那里得到输入:
var location_keyword = $("#si_user_location").val();
现在,我想用"|"替换空白"可以在我的正则表达式中将其用作OR.
例如,如果用户写了"Turkey Alanya",我希望它是"Turkey | Alanya",这样搜索就可以同时找到"Turkey"或"Alanya".
我尝试了类似的方法,但是没有用
var location_keyword = $("#si_user_location").val();
location_keyword.replace(" ","|");
var regexp_loc = new RegExp(location_keyword, "i");
我以前曾在PHP中使用以下表达式来实现此目的:
preg_replace('/'.preg_quote($keyword).'/i', "<span>$0</span>", $string)
并且我可以像这样替换字符串caseinsensetive,如何在js中做到这一点?
我使用了PHP中的最后一个表达式来突出显示结果中的关键字,我希望在js中也能做到这一点.
希望我能得到一些帮助,在此先感谢您! :)
致以最诚挚的问候, 亚历山大使用 replace
:
location_keyword.replace(" ","|");
- 它不修改字符串-它返回一个新字符串.您需要将调用结果重新分配给原始变量,否则您将看不到更改后的字符串.
- 除非您使用带有
g
(全局)标志的正则表达式,否则它仅替换第一次出现的情况.
尝试以下方法:
location_keyword = location_keyword.replace(/ /g, '|');
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, '|');
这篇关于javascript javascript regexp替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!