Parsing an Int from a string in javascript

前端 未结 3 1337
难免孤独
难免孤独 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: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.

提交回复
热议问题