修改字符串末尾的整数

杰森·凯利(Jason Kelly)

我需要你的帮助,

我需要的是一个javscript函数,可以完成以下两项操作之一:

首先,如果给定一个字符串,即。var x = "filenumber"该函数在调用时将处理字符串,并在字符串末尾添加-2,var x = "filenumber-2"如果字符串的末尾不存在-2 ,则结果为-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>
钟洁

简短说明:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章