[Solved] How to get numbers out of string into array [duplicate]


You can use String#match with a RegExp. You can use Array#map afterwards to convert the strings to numbers if needed.

var str="156p1m2s33c";

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

console.log(numbers);

What’s wrong in your code:

  1. cust_code and url are not part of the function. Refer to str.
  2. You declare prodId twice.
  3. You don’t handle the number between “s” and “c”.
  4. You are doing a lot of duplicated search (index of p, index of m, etc…).
  5. Your function doesn’t return anything, or do anything with the results.
  6. Using regular expressions is more fitting for this case.
function myFunction() {
    var str = "156p1m2s33c";
    var pI = str.indexOf('p');
    var mI = str.indexOf('m');
    var sI = str.indexOf('s');
    var cI = str.indexOf('c');
    
    var prodId = str.substring(0, pI);
    var metalId = str.substring(pI + 1, mI);
    var anotherId1 = str.substring(mI + 1, sI);
    var anotherId2 = str.substring(sI + 1, cI);
    
    return [prodId, metalId, anotherId1, anotherId2];
}

console.log(myFunction());

0

solved How to get numbers out of string into array [duplicate]