Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing an Int from a string in javascript

Tags:

In javascript, what is the best way to parse an INT from a string which starts with a letter (such as "test[123]")? I need something that will work for the example below.

My JS:

$(document).ready(function() {      $(':input').change( function() {         id = parseInt($(this).attr("id"));  //fails for the data below         alert(id);     }); } 

My generated HTML:

<select id="attribute[123]"> <!-- various options --> </select> <select id="attribute[456]"> <!-- various options --> </select> 

Thank you!

like image 947
Wickethewok Avatar asked Jan 15 '09 22:01

Wickethewok


People also ask

How do I convert a string to an int in JavaScript?

To convert a string to an integer parseInt() function is used in javascript. parseInt() function returns Nan( not a number) when the string doesn't contain number. If a string with a number is sent then only that number will be returned as the output.

Why we use parse int in JavaScript?

The main purpose of using the parseInt function is to extract a number from a string. This turns the returned value to an actual number. In the example above, 3 is a string and not an actual number.

How can a string be converted to a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.


2 Answers

You could use a regular expression to match the number:

$(this).attr("id").match(/\d+/) 
like image 182
Gumbo Avatar answered Oct 20 '22 06:10

Gumbo


parseInt(input.replace(/[^0-9-]/,""),10) 
like image 43
Joel Coehoorn Avatar answered Oct 20 '22 06:10

Joel Coehoorn