javascript替换查询字符串值
问题描述:
可能的重复:
添加或更新查询字符串参数
我试图替换查询字符串中的页码,无论哪个数字是 1.
I am trying to replace the page number in the query string no matter what digit is to 1.
查询字符串
index.php?list&page=2&sort=epub
javascript
window.location.href.replace(new RegExp("/page=.*?&/"), "page=1&")
答
你的代码看起来几乎正确;然而:
Your code looks almost right; however:
- 您需要使用要么
new RegExp
或特殊的//
正则表达式语法,但不能同时使用. -
replace
方法不会就地修改字符串,它只是返回修改后的副本. - 而不是
.*?
,我觉得写\d+
更有意义;如果您没有想到,更精确的正则表达式通常不太可能出错.
- you need to use either
new RegExp
or the special//
regex syntax, but not both. - the
replace
method doesn't modify the string in-place, it merely returns a modified copy. - rather than
.*?
, I think it makes more sense to write\d+
; more-precise regexes are generally less likely to go awry in cases you haven't thought of.
所以,把它放在一起:
window.location.href = window.location.href.replace(/page=\d+/, "page=1");