0

Well, though I searched for learning sources I could not find the exact thing I wanted. Please help to improve this post rather than down-voting so that all new learners can improve their knowledge.

lets assume there is a variable

var y = "number12";

var z ="";
  1. how to make z=12 (how take only the integer value out of y string variable)
  2. how to make z=number13 (adding one to "number"+12 )
3
  • 1
    Have a look for "regular expressions". Alternatively you could try to split a string of this pattern into the non-number part and the number part (starting at the end of the string, checking if this character is still 0-9, going backwards, repeat). Increment the number part and combine those two parts back to a string again. Commented Sep 17, 2014 at 14:05
  • 1
    Does the string always end in a number? Is the number text constant? Commented Sep 17, 2014 at 14:10
  • @Alex K. yes number is a constant Commented Sep 17, 2014 at 14:20

4 Answers 4

1

Extract the number with a RegEx and then use parseInt to convert the string "12" to the number 12.

var y = "number12";
var x = parseInt( y.match(/\d+/) );
alert(x)

Sign up to request clarification or add additional context in comments.

2 Comments

what is the difference between x = parseInt(y.match(/[\d\.]*/)); and var x = parseInt( y.match(/\d+/) );
The \d matches a single digit like 1 and \d+ matches one or more digits like 12. \d* would match zero or one digits.[\d\.]* doesn't appear to work. For mor info about regexes: regular-expressions.info/tutorial.html
1

You may try this,

var y = "number12";
x = parseInt(y.match(/[\d\.]*/));

Comments

1

Given that: @Alex K. yes number is a constant

Simply:

var x = "number" + (+y.substr(6) + 1);

1 Comment

@ Alex K. can you expain what is the difference between x = parseInt(y.match(/[\d\.]*/)); and var x = parseInt( y.match(/\d+/) );
0

I agree with matthias

var input = "number12";

// define a regular expression to match your pattern
var re = /(\D+)(\d+)/;

// execute the regexp to get an array of matches
var parsed = re.exec(input);  // ['number12', 'number', '12']

// parse an integer value of the number
parsed[2] = parseInt(parsed[2], 10); // '12' ==> 12

// increment the number
parsed[2] += 1; // 12 ==> 13

// rejoin the string
input = parsed[1] + parsed[2]; // 'number' + 13 ==> 'number13'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.