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:
cust_code
andurl
are not part of the function. Refer tostr
.- You declare
prodId
twice. - You don’t handle the number between “s” and “c”.
- You are doing a lot of duplicated search (index of p, index of m, etc…).
- Your function doesn’t return anything, or do anything with the results.
- 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]