views:

667

answers:

3

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!

+8  A: 
parseInt(input.replace(/[^0-9-]/,""),10)
Joel Coehoorn
Interestingly, this will NOT work if given valid float literals like "1e10"
Triptych
I don't think this will work at all without the global flag.
Prestaul
Of course it won't work for floats. The op specifically asked about ints.
Joel Coehoorn
A: 

Probably just filter out the string with .replace(). If there is another way then I am unaware of it:

parseInt("attribute[123]".replace("attribute[", "").replace("]", "")));

You could probably use some Regex to put that in only one .replace(), but I'm not good with Regex so I just did it twice.

Test this in your browser with

javascript:alert(parseInt("attribute[123]".replace("attribute[", "").replace("]", "")));

Should alert 123.

Logan Serman
+15  A: 

You could use a regular expression to match the number:

$(this).attr("id").match(/\d+/)
Gumbo
Checkmark for succinctness and readability. Thanks to all though. : )
Wickethewok
Note that the regex should be changed to "/[-+]?\d+/" for a more general case (to allow signed ints), but that looks unnecessary for the OP's situation.
Ben Blank
What would make it more robust is to do $(this).attr("id").match(/\[(\d+)\]/)[1] since that would allow things like "attribute7[123]"
PEZ
@PEZ, nice refinement.
Prestaul