在JS中基于其前面的子字符串增加字符串中的数字 [英] Increment a number in a string based on the substring before it in JS

查看:170
本文介绍了在JS中基于其前面的子字符串增加字符串中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在网址中增加一个数字,该数字始终以页面/ 开头,所以像 page / 2 / 然而,url可以以任何方式构建,甚至可以包含其他数字。

I need to increment a number in a url, the number is always preceded by page/ so like page/2/ however the url could be constructed any which way and may even contain other numbers.

这是我的工作但增加了所有数字而不仅仅是遵循 page / 。我需要做什么才能将其限制为只有页面/ 前面的数字?

Here's what I have which works but increments all numbers rather than just the one that follows page/. What do I need to do to limit it to only the number preceded by page/?

let link = '//localhost:3000/insight/page/2/';
let next = link.replace(/\d+/g, function(n){ return ++n });

console.log(next)

//Outputs '//localhost:3001/insight/page/3/'

//Needs to be '//localhost:3000/insight/page/3/'

这是一个轻松的代码: https://codepen.io/matt3224/pen/brrEQB?editors=1111

Here's a codepen for ease: https://codepen.io/matt3224/pen/brrEQB?editors=1111

非常感谢

@adeneo解决方案

SOLUTION by @adeneo

let link = '//localhost:3000/insight/page/2/';
let next = link.replace(/page\/(\d+)\//, (x,y) => `page/${(++y)}/`);


推荐答案

匹配页面之间的任何数字/ / 应该有效,无论其他数字或URL出现在哪里

Matching any numbers between page/ and / should work, regardless of other numbers or where in the URL it occurs

let link = '//localhost:3000/insight/page/2/';
let next = link.replace(/page\/(\d+)\//, (x,y) => 'page/' + (++y) + '/');

console.log(next)

test( '//localhost:3000/insight/page/2/' );
test( '//localhost:3000/insight/page/2/more/here' );
test( '//localhost:3000/page/2/' );
test( '//localhost:3000/insight/page/2/2/2/2/' );

function test(link) {
	var next = link.replace(/page\/(\d+)\//, (x,y) => 'page/' + (++y) + '/');
	console.log(next)
}

这篇关于在JS中基于其前面的子字符串增加字符串中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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