最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get multiple character positions in array? - Stack Overflow

programmeradmin0浏览0评论

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

w.wer,ads,

should give something like:

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

How can this be done with javascript?

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

w.wer,ads,

should give something like:

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

How can this be done with javascript?

Share Improve this question asked Mar 13, 2012 at 19:07 lisovaccarolisovaccaro 34k99 gold badges270 silver badges423 bronze badges 1
  • Your example isn't clear, do you want the ma and dot index? – Dor Cohen Commented Mar 13, 2012 at 19:12
Add a ment  | 

9 Answers 9

Reset to default 4
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]

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,", [".", ","]);

Option 1

Simply loop through each character in the string:

var myString = "w.wer,ads,";
var matchedIndexes = [];

for (var i = 0; i < myString.length; i++) {
    if (myString[i] == "," || myString[i] == ".") {
        matchedIndexes.push(i);
    }
}

Here's a working fiddle.

Option 2

If you wanted to get a bit fancier with it, you could create an object that stores the position and the character at that position:

var myString = "w.wer,ads,";
var matchedIndexes = [];

for (var i = 0; i < myString.length; i++) {
    if (myString[i] == "," || myString[i] == ".") {
        matchedIndexes.push(new myMatch(myString[i], i));
    }
}

function myMatch(position, character) {
    this.position = position;
    this.character = character;
}

Result:

Here's a working fiddle.

function dotsAndCommas(s) {
  var rv = [];
  for (var i = 0; i < s.length; ++i) {
    if (s[i] === '.' || s[i] === ',') rv.push(i);
  }
  return rv;
}

Basically, just do it. There's no shortcut way I can think of to do it with a regex.

Probably not ideal, but as a thought experiment, here is a way to do it with built-in javascript functions (no explicit loops):

var pos = mystr.split(/[,.]/).slice(0,-1).map(function(val, i, a) { return a.slice(0, i+1).join('').length+i; });

Demo: http://jsfiddle/jtbowden/hHSB2/

To get rid of the nested .slice() which is O(n^2):

var pos = mystr.split(/[,.]/).slice(0,-1).map(function(val, i, a) { return a[i] = val.length+(a[i-1]||-1)+1; });

Demo: http://jsfiddle/jtbowden/hHSB2/1/

And, yes, it is still ugly and pointless.

Yet another almost one-liner:

var q = [];
[].forEach.call('w.wer,ads,', function(v, i) { /[,.]/.test(v) ? q.push(i) : 0 } );
// q == [1,5,9]

I would loop through the string and check each character like so:

    var s = "w.wer,ads,";

    var arr = new Array();

    for( var i = 0; i < s.length; i++ ) {

    if( s.charAt(i) == "." || s.charAt(i) == "," )
        arr.push(i);
    }

    for( var i = 0; i < arr.length; i++ ) {
        document.write( arr[i] );
    }

Since there're 5 solutions already, I'll write my almost one-liner.

function dotsAndCommasPositions(str) {
    var i = -1;
    return str.split(/[.,]/).slice(0, -1).map(function(s){ return i += s.length + 1; });
};

You can create a function that loops through all the characters and saves the index of . and ,.

​function getPositionsOfDotsCommas(str) {
    var result = [];

    for (var i = 0; i < str.length; i++) {
        if (str[i] === '.' || str[i] === ',') {
            result.push(i);
        }        
    }

    return result;
}​
发布评论

评论列表(0)

  1. 暂无评论