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!
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.
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.
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.
You could use a regular expression to match the number:
$(this).attr("id").match(/\d+/)
parseInt(input.replace(/[^0-9-]/,""),10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With