如何使用Javascript或Jquery增加字符串中的数字 [英] How to increment number in string using Javascript or Jquery

查看:57
本文介绍了如何使用Javascript或Jquery增加字符串中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的textarea的id是字符串,格式为

The id of my textarea is string and of this format


id ='fisher [27] .man'

id='fisher[27].man'

我想克隆textarea并增加数字并获取id fisher [28] .man 并将其添加到现有的textarea。

I would like to clone the textarea and increment the number and get the id as fisher[28].man and prepend this to the existing textarea.

有没有办法通过jquery轻松完成这项工作?

Is there a way to get this done easily with jquery?

var existingId = $("#at textarea:last").attr('id');
var newCloned = lastTextArea.clone();
var newId = newCloned.attr('id');
//add the index number after spliting
//prepend the new one to 
newCloned.prepend("<tr><td>" + newCloned + "</td></tr>");

必须有更简单的克隆方法,获取索引号,拆分和前置。

There has to be easier way to clone, get index number, split and prepend.

我也尝试用regEx做到这一点

I'm have also tried to do this with regEx

var existingIdNumber = parseInt(/fisher[(\d+)]/.exec(s)[1], 10);

任何人都可以帮我这个吗?

Can anybody help me with this?

推荐答案

正确的正则表达式是这个

Correct regex would be this

/fisher\[\d+\].man/

这是一个通过它你将提取id。

Here is a way through through which you would extract the the id.

id = text.replace(/fisher\[(\d+)\].man+/g,"$1");
//Now do whatever you want with the id

做任何你想做的事情同样,相同的替换技术可以是用于获得增加的ID为:

Similarly, Same replacement technique can be used to get an incremented id as:

existingId = 'fisher[27].man';
newId = existingId .replace(/(\d+)+/g, function(match, number) {
       return parseInt(number)+1;
});
console.log(newId);

这篇关于如何使用Javascript或Jquery增加字符串中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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