Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get multiple character positions in array?

Tags:

javascript

I want to get position of dots and commas in an array.

w.wer,ads,

should give something like:

[0] > 1
[1] > 5
[2] > 9

How can this be done with javascript?

like image 600
lisovaccaro Avatar asked Feb 20 '26 22:02

lisovaccaro


2 Answers

function getPositions(regex, str) {
    var counts = [], m;
    while (m = regex.exec(str)) {
        counts.push(regex.lastIndex - m[0].length);
    }
    return counts;
}

// Usage:
getPositions(/[,.]/g, 'w.wer,ads,'); // => [1,5,9]
like image 192
James Avatar answered Feb 22 '26 10:02

James


Try the following

var getAllIndexesOf = function(str, toFind) {
  var all = [];
  for (var i = 0; i < str.length; i++) {
    if (toFind.indexOf(str[i]) >= 0) {
      all.push(i);
    }
  }
  return all;
}

var result = getAllIndexsOf("w.wer,ads,", [".", ","]);
like image 38
JaredPar Avatar answered Feb 22 '26 10:02

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!