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 )
nimala9
  • 201
  • 1
  • 2
  • 6
  • 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. – matthias Sep 17 '14 at 14:05
  • 1
    Does the string always end in a number? Is the `number` text constant? – Alex K. Sep 17 '14 at 14:10
  • @Alex K. yes number is a constant – nimala9 Sep 17 '14 at 14:20

4 Answers4

1

You may try this,

var y = "number12";
x = parseInt(y.match(/[\d\.]*/));
Tony Yip
  • 705
  • 5
  • 14
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)
mb21
  • 34,845
  • 8
  • 116
  • 142
  • what is the difference between x = parseInt(y.match(/[\d\.]*/)); and var x = parseInt( y.match(/\d+/) ); – nimala9 Sep 17 '14 at 14:23
  • 1
    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: http://www.regular-expressions.info/tutorial.html – mb21 Sep 17 '14 at 14:26
1

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

Simply:

var x = "number" + (+y.substr(6) + 1);
Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • @ Alex K. can you expain what is the difference between x = parseInt(y.match(/[\d\.]*/)); and var x = parseInt( y.match(/\d+/) ); – nimala9 Sep 17 '14 at 14:26
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'
Community
  • 1
  • 1
pgoldrbx
  • 31
  • 3