Faizan
Faizan

Reputation: 776

Convert String to int in Jquery

string title = "title1";

If I want to make it title2 how can I?

as I cant convert whole as int, may something like cropping or trimming ?

title suffix(1) is not a fixed number

just I want to alter the last digit which always be a int

Upvotes: 1

Views: 202

Answers (4)

Faizan
Faizan

Reputation: 776

This answer solved my Problem, the most dynamic way to do so...

var title = "title1";
var i = title.substr(5);
var newTitle = ("title" + ++i);

Upvotes: -1

huysentruitw
huysentruitw

Reputation: 28151

Since the number can be more than one char, the answer using splice will not work.

So it's best to first get the number and increment it:

var title = "title1";
var i = title.substr(5);
console.log("title" + ++i);

Output

title2

Upvotes: 1

Karthik Rao
Karthik Rao

Reputation: 320

title = title.slice(0,(title.indexOf('e')+1)-title.length) + '2';

This will remove all characters after the letter 'e' in title and add the number at the end

Upvotes: -1

adeneo
adeneo

Reputation: 318342

title = title.slice(0,-1) + (+title.replace(/\D/g, '') + 1);

FIDDLE

or

title = title.slice(0,-1) + (+title.slice(-1) + 1);

or

title = title.replace(/\d+/g, function(x) {return ++x});

Upvotes: 2

Related Questions