javascript - 替换 URL 中 id 的值

标签 javascript html string function url

我有这种形式的 URL:

https://www.merkel.com/obama?trump=15&id=9616071454&hilarry=es

我想通过 例如,将 9616071454 替换为 1。

我知道 replace() ,但这将替换“id”本身,不是“id”的值。

Web 开发世界中有什么共同点吗? :)

最佳答案

考虑以下情况的解决方案:

  • id参数可以包含数字以外的其他字符
  • id 后跟 # 时避免片段 # 替换

var str = 'https://www.foo.com/bar?trump=15&hilarry=es&id=961607some1454text#fragment',
    newId = 1,
    replaced = str.replace(/\bid=[^&#]+/g, "id=" + newId);

console.log(replaced); // "https://www.foo.com/bar?trump=15&hilarry=es&id=1#fragment"

关于javascript - 替换 URL 中 id 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39319329/

相关文章:

python - 根据空格和标点符号进行标记,保留标点符号

c - 在 C 中,打印字符串后 "at"符号

javascript - 使用javascript如何克服ie版本的document.createElement ('script' .onload问题

javascript - 如何从页面中临时删除 iframe,然后在不重新下载 iframe 内容的情况下重新添加 iframe?

javascript - 单击 html 选择选项时显示额外的表单输入字段

html - 占位符在输入字段内自动换行

javascript - 正则表达式匹配末尾有 n 个重复数字的数字

javascript - 函数调用返回 API 结果后异步更新状态

javascript - 使用 jQuery 移动 ajax 导航加载多页面模板

PHP 从行中获取第一个单词