修改字符串末尾的整数

Modifying the integer at the end of a string

本文关键字:整数 字符串 修改      更新时间:2023-09-26

我需要你的帮助,

我需要的是一个 javscript 函数,它可以完成以下两件事之一:

首先,如果给定一个字符串,即。 var x = "filenumber"调用函数时,将处理字符串并在其末尾添加 -2,如果字符串末尾不存在 -2,则会导致var x = "filenumber-2"

其次,如果给定的值,var x is already = "filenumber-2"取字符串末尾的数字并将其递增 1,导致 var x = "filenumber-3". 之后每次第四次递增数字,如果再次调用该函数。

下面是概念标记:

<DOCYTPE HTML>
<html>
<head>
<script type="text/javascript">
function test(){
var x = document.getElementById('input').value
1.) if x doesnt already have the -2 at the end of the string then add it:
document.getElementById('output').value = x + "-2"

2.) else, the function recognizes that it does and the result of the output is
x-2 + 1
}
</script>
</head>
<body>
<input type="text" id="input"/>
<br>
<input type="text" id="output"/>
<br>
<input type="button" onclick="test()" value="test"/>
</body>
</html>

Short 'n sweet:

x = 'filenumber-4';
x = x.replace(/^(.+?)(-'d+)?$/, function(a,b,c) { return c ? b+(c-1) : a+'-2'; } );