Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment number in string using Javascript or Jquery

Tags:

javascript

The id of my textarea is string and of this format

id='fisher[27].man'

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.

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.

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?

like image 513
user983208 Avatar asked Mar 20 '12 04:03

user983208


3 Answers

Correct regex would be this

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

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

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);

Demo with both usage

like image 76
Starx Avatar answered Nov 12 '22 18:11

Starx


Another easy solution from this question's accepted answer:

'url1'.replace(/\d+$/, function(n){ return ++n }); // "url2"
'url54'.replace(/\d+$/, function(n){ return ++n }); // "url55"

Very clean and readable.

like image 44
rodamn Avatar answered Nov 12 '22 18:11

rodamn


jsFiddle Demo

No need for all the extra code. Change this line:

var newId = newCloned.attr('id');

To:

var newId  = newCloned.attr('id').replace( /(\d+)/, function(){return arguments[1]*1+1} );
like image 3
vol7ron Avatar answered Nov 12 '22 18:11

vol7ron