get all numbers in a string and push to an array (javascript)

前端 未结 2 501
青春惊慌失措
青春惊慌失措 2021-01-26 17:40

So if I had the following string:

\'(01) Kyle Hall - Osc (04) Cygnus - Artereole (07) Forgemasters - Metalic (10) The Todd Terry Project - Back to the Beat (14)          


        
2条回答
  •  没有蜡笔的小新
    2021-01-26 18:30

    Use a regular expression:

    var numbers = str.match(/\d+/g);
    

    This will result in ["01", "04", "07", "10", "14"] (array of strings). If the type of the elements matters to you you can follow up with .map(Number) to convert to numbers:

    var reallyNumbers = str.match(/\d+/g).map(Number);
    

    which will result in [1, 4, 7, 10, 14].

    Note that map is not available in IE earlier than version 9, so depending on your compat requirements you might need a polyfill. There's a ready-made one on MDN.

提交回复
热议问题