1
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

3
  • 2
    title = title.replace('1', '2'); Commented Jan 11, 2014 at 8:50
  • 1
    title = title.slice(0,-1) + 2; Commented Jan 11, 2014 at 8:51
  • if title1's '1' is unknown number then?? Commented Jan 11, 2014 at 8:52

4 Answers 4

2
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});
Sign up to request clarification or add additional context in comments.

2 Comments

return (+x)+1 can be written as return ++x
@WouterHuysentruit Yes it can, and \d+ would match numbers higher than 9
1

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

Comments

-1
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

Comments

-1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.