正则表达式:如何替换包含数字的字符串(作为变量)?

时间:2015-05-13 13:36:03

标签: javascript regex replace

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

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

我试过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

我错过了什么?

5 个答案:

答案 0 :(得分:1)

也许你的意思是



var url = 'http://mywebsite.com/?&filters[]=price_gte:20';
var path = 'filters[]=price_gte:';
var value = 10;
var re = /filters\[\]=price_[g|l]te:\d+/;
alert(url.replace(re,path+value))




然而,更好的解决方案可能是



// from http://stackoverflow.com/a/20420424/295783

function replaceUrlParam(url, paramName, paramValue){
    var pattern = new RegExp('('+paramName+'=).*?(&|$)')
    var newUrl=url
    if(url.search(pattern)>=0){
        newUrl = url.replace(pattern,'$1' + paramValue + '$2');
    }
    else{
        newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
    }
    return newUrl
}

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

url = replaceUrlParam(url,"filters[]", 'price_gte:'+value);
alert(url)




答案 1 :(得分:1)

你几乎就在那里,只需要摆脱括号:

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));

答案 2 :(得分:0)

这似乎对我有用:

function replace() {
                var url = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:200';
                var path = '&filters[]=price_gte:';
                var value = 10;

                var newStr = url.replace(/&filters\[\]=price_gte:\d+/, "&filters[]=price_gte:" + value);
                alert(newStr);
            }

答案 3 :(得分:0)

这足以获得新价值

var str = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:100';
var pattern = /price_gte:\d+/;
var new_value = 10;
str = str.replace(patter, 'price_gte:'+new_value);

答案 4 :(得分:0)

简单的解决方案将是=>

function replace() {
            var url = 'http://mywebsite.com?&filters[]=price_gte:20&filters[]=price_lte:200';
            var path = '&filters[]=price_gte:';
            var value = 10;

            var newStr = url.replace(/(\w*)(price_gte:)(\d*)/i,"price_gte:"+ value);
            alert(newStr);
        }