gpt4 book ai didi

javascript - 正则表达式 : how to replace a string (as a variable) that has a digit in it?

转载 作者:行者123 更新时间:2023-11-30 16:52:58 24 4
gpt4 key购买 nike

var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = '&filters[]=price_gte:';
var value = 10;

如何用新路径替换 &filters[]=price_gte:20 部分? (路径 + 值)

我试过RegExp():

var re = new RegExp(path);
console.log(url.replace(re, ''));
//returns http://mywebsite.com/?&filters[]=price_gte:20

这甚至没有用,更不用说在正则表达式中添加数字了。问题是,price_gte 是一个变量(price_lte 也是,以及可能出现的任何其他范围),它后面有一个可变数字。

我掌握的信息:

  • url (http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:100)
  • 路径(&filters[]=price_gte:)
  • 新值(10)

期望的结果:

  • http://mywebsite.com?&filters[]=price_gte:10&filters[]=price_lte:100

我错过了什么?

最佳答案

你几乎就在那里,只需要避开括号:

var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = '&filters[]=price_gte:';
var regexPath = '&filters\\[\\]=price_gte:\\d+';
var value = 10;
var re = new RegExp(regexPath);

console.log(url.replace(re, path+value));

关于javascript - 正则表达式 : how to replace a string (as a variable) that has a digit in it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30216536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com