用编辑后的子字符串替换子字符串

Replace substring with edited substring

请你帮我完成我的任务:我需要替换部分字符串,最好的方法可能是正则表达式,但我不知道如何让它工作。我想这样做:

http://someweb.com/section/&limit=10&page=2

page=2 替换为 page=3 因此字符串将是:

http://someweb.com/section/&limit=10&page=3

我试过这样做:

// set string in t variable
t.replace('/page=[0-9]/', 'page=++') });

非常感谢您的帮助:)

在我们的例子中,第一个参数应该是正则表达式,但在你的变体中,这是字符串 '/page=[0-9]/'(删除 ')。在 replace 中,您可以将函数作为第二个参数传递,并根据需要对匹配的数据进行处理。 (例如将 +1 添加到 page=

var str = "http://someweb.com/section/&limit=10&page=2";

str.replace(/page=(\d+)/, function (match, page) {
  return 'page=' + (+page + 1); // plus before page converts string to number
});

Example

您也可以试试下面的代码。

var url = "http://someweb.com/section/&limit=10&page=2",
    reExp = /page=([0-9])+/,
    result = reExp.exec(url);

url = url.replace(reExp, 'page=' + (+result[1] + 1));
console.log(url)