Parsing an Int from a string in javascript

前端 未结 3 1276
难免孤独
难免孤独 2020-12-02 17:27

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.

相关标签:
3条回答
  • 2020-12-02 18:13
    parseInt(input.replace(/[^0-9-]/,""),10)
    
    0 讨论(0)
  • 2020-12-02 18:15

    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.

    0 讨论(0)
  • 2020-12-02 18:16

    You could use a regular expression to match the number:

    $(this).attr("id").match(/\d+/)
    
    0 讨论(0)
提交回复
热议问题