+ 2

How to get available number from string in JavaScript?

I want to get available number from a string in JavaScript. Eg: var id = "A0001"; //I want get 0001 or 1 from that string I'd Please help me

13th Apr 2019, 1:22 AM
Mohammed Ashad
Mohammed Ashad - avatar
7 Réponses
+ 5
You can use the slice method like so: string.slice(startIndex, endIndex) In your case: id.slice(1) To obtain an integer: Number(id.slice(1)) EDIT: to remove non numeric characters from a string, Calvin's suggestion using the .replace method + regex is the golden standard 👌
13th Apr 2019, 1:35 AM
Nic!
Nic! - avatar
+ 5
Get a varible of number from any string that contains numbers var number = parseInt(id.replace(/\D/,''),10)
13th Apr 2019, 1:55 AM
Calviղ
Calviղ - avatar
+ 4
I have made a demo code. Calviղ and Nic! I think this method also works. https://code.sololearn.com/WmZNOp0KnRLx/?ref=app
13th Apr 2019, 2:05 AM
Sarthak Pokhrel
Sarthak Pokhrel - avatar
+ 2
Space careful your parameters need to be consistent 😉 with some cleaning your fn does work 👍take a look at regexes they're the built-in tool for the job
13th Apr 2019, 2:42 AM
Nic!
Nic! - avatar
+ 2
Nic! Now its perfect
13th Apr 2019, 2:58 AM
Sarthak Pokhrel
Sarthak Pokhrel - avatar
+ 1
Nic! Calvin's replace way and Space's and your splice way both have its own limitations. Can you illustrate the difference with examples?
13th Apr 2019, 3:07 AM
Gordon
Gordon - avatar
+ 1
Use int
13th Apr 2019, 3:01 PM
verio elfando