javascript替换查询字符串值 [英] javascript replace query string value

查看:29
本文介绍了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");

这篇关于javascript替换查询字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆