25

In JavaScript, how 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>

3 Answers 3

58

You could use a regular expression to match the number:

$(this).attr("id").match(/\d+/)
Sign up to request clarification or add additional context in comments.

4 Comments

Checkmark for succinctness and readability. Thanks to all though. : )
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.
What would make it more robust is to do $(this).attr("id").match(/\[(\d+)\]/)[1] since that would allow things like "attribute7[123]"
an explanation here would be very helpful.
25
parseInt(input.replace(/[^0-9-]/,""),10)

2 Comments

Interestingly, this will NOT work if given valid float literals like "1e10"
Of course it won't work for floats. The op specifically asked about ints.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.