Javascript 查找字符串中指定字符的所有索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10710345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding all indexes of a specified character within a string
提问by Ageis
For example if I had "scissors"
in variable and wanted to know the position of all occurrences of the letter "s"
, it should print out 1, 4, 5, 8
例如,如果我有"scissors"
in 变量并想知道所有出现的字母的位置"s"
,它应该打印出来1, 4, 5, 8
How can I do this in JavaScript in most efficient way? I don't think looping through the whole is terribly efficient
我怎样才能以最有效的方式在 JavaScript 中做到这一点?我不认为遍历整个过程非常有效
回答by vcsjones
A simple loop works well:
一个简单的循环效果很好:
var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "s") indices.push(i);
}
Now, you indicate that you want 1,4,5,8. This will give you 0, 3, 4, 7 since indexes are zero-based. So you could add one:
现在,您表明您想要 1、4、5、8。这将为您提供 0、3、4、7,因为索引是从零开始的。所以你可以添加一个:
if (str[i] === "s") indices.push(i+1);
and now it will give you your expected result.
现在它会给你你预期的结果。
A fiddle can be see here.
一个小提琴可以在这里看到。
I don't think looping through the whole is terribly efficient
我不认为遍历整个过程非常有效
As far as performance goes, I don't think this is something that you need to be gravely worried about until you start hitting problems.
就性能而言,我不认为这是您在开始遇到问题之前需要严重担心的事情。
Here is a jsPerftest comparing various answers. In Safari 5.1, the IndexOf performs the best. In Chrome 19, the for loop is the fastest.
这是一个比较各种答案的jsPerf测试。在 Safari 5.1 中,IndexOf 表现最好。在 Chrome 19 中,for 循环是最快的。
回答by Phrogz
Using the native String.prototype.indexOf
method to most efficiently find each offset.
使用本机String.prototype.indexOf
方法最有效地找到每个偏移量。
function locations(substring,string){
var a=[],i=-1;
while((i=string.indexOf(substring,i+1)) >= 0) a.push(i);
return a;
}
console.log(locations("s","scissors"));
//-> [0, 3, 4, 7]
This is a micro-optimization, however. For a simple and terse loop that will be fast enough:
然而,这是一个微观优化。对于一个足够快的简单而简洁的循环:
// Produces the indices in reverse order; throw on a .reverse() if you want
for (var a=[],i=str.length;i--;) if (str[i]=="s") a.push(i);
In fact, a native loop is faster on chrome that using indexOf
!
事实上,原生循环在 chrome 上比使用indexOf
!
回答by Chad Scira
When i benchmarked everything it seemed like regular expressions performed the best, so i came up with this
当我对所有内容进行基准测试时,正则表达式似乎表现最好,所以我想出了这个
function indexesOf(string, regex) {
var match,
indexes = {};
regex = new RegExp(regex);
while (match = regex.exec(string)) {
if (!indexes[match[0]]) indexes[match[0]] = [];
indexes[match[0]].push(match.index);
}
return indexes;
}
you can do this
你可以这样做
indexesOf('ssssss', /s/g);
which would return
哪个会返回
{s: [0,1,2,3,4,5]}
i needed a very fast way to match multiple characters against large amounts of text so for example you could do this
我需要一种非常快速的方法来将多个字符与大量文本进行匹配,例如您可以这样做
indexesOf('dddddssssss', /s|d/g);
and you would get this
你会得到这个
{d:[0,1,2,3,4], s:[5,6,7,8,9,10]}
this way you can get all the indexes of your matches in one go
通过这种方式,您可以一次性获得所有匹配项的索引
回答by Tomalak
function charPos(str, char) {
return str
.split("")
.map(function (c, i) { if (c == char) return i; })
.filter(function (v) { return v >= 0; });
}
charPos("scissors", "s"); // [0, 3, 4, 7]
Note that JavaScript counts from 0. Add +1 to i
, if you must.
请注意,JavaScript 从 0 开始计数i
。如果必须,请将+1 添加到。
回答by davnicwil
More functional fun, and also more general: This finds the starting indexes of a substring of anylength in a string
功能更有趣,也更通用:这将查找字符串中任意长度的子字符串的起始索引
const length = (x) => x.length
const sum = (a, b) => a+b
const indexesOf = (substr) => ({
in: (str) => (
str
.split(substr)
.slice(0, -1)
.map(length)
.map((_, i, lengths) => (
lengths
.slice(0, i+1)
.reduce(sum, i*substr.length)
))
)
});
console.log(indexesOf('s').in('scissors')); // [0,3,4,7]
console.log(indexesOf('and').in('a and b and c')); // [2,8]
回答by tpdi
indices = (c, s) => s
.split('')
.reduce((a, e, i) => e === c ? a.concat(i) : a, []);
indices('?', 'a?g??'); // [1, 3, 4]
回答by Yash Kalwani
You could probably use the match() function of javascript as well. You can create a regular expression and then pass it as a parameter to the match().
您也可以使用 javascript 的 match() 函数。您可以创建一个正则表达式,然后将其作为参数传递给 match()。
stringName.match(/s/g);
This should return you an array of all the occurrence of the the letter 's'.
这应该返回一个包含所有出现的字母“s”的数组。
回答by hygull
I loved the question and thought to write my answer by using the reduce()
method defined on arrays.
我喜欢这个问题,并想通过使用reduce()
定义在数组上的方法来写我的答案。
function getIndices(text, delimiter='.') {
let indices = [];
let combined;
text.split(delimiter)
.slice(0, -1)
.reduce((a, b) => {
if(a == '') {
combined = a + b;
} else {
combined = a + delimiter + b;
}
indices.push(combined.length);
return combined; // Uncommenting this will lead to syntactical errors
}, '');
return indices;
}
let indices = getIndices(`Ab+Cd+Pk+Djb+Nice+One`, '+');
let indices2 = getIndices(`Program.can.be.done.in.2.ways`); // Here default delimiter will be taken as `.`
console.log(indices); // [ 2, 5, 8, 12, 17 ]
console.log(indices2); // [ 7, 11, 14, 19, 22, 24 ]
// To get output as expected (comma separated)
console.log(`${indices}`); // 2,5,8,12,17
console.log(`${indices2}`); // 7,11,14,19,22,24
回答by alireza
Just for further solution, here is my solution: you can find character's indexes which exist in a string:
只是为了进一步的解决方案,这是我的解决方案:您可以找到存在于字符串中的字符索引:
findIndex(str, char) {
const strLength = str.length;
const indexes = [];
let newStr = str;
while (newStr && newStr.indexOf(char) > -1) {
indexes.push(newStr.indexOf(char) + strLength- newStr.length);
newStr = newStr.substring(newStr.indexOf(char) + 1);
}
return indexes;
}
findIndex('scissors', 's'); // [0, 3, 4, 7]
findIndex('Find "s" in this sentence', 's'); // [6, 15, 17]
回答by Richard
Here is a short solution using a function expression (with ES6 arrow functions). The function accepts a string and the character to find as parameters. It splits the string into an array of characters and uses a reduce
function to accumulate and return the matching indices as an array.
这是使用函数表达式(使用 ES6 箭头函数)的简短解决方案。该函数接受一个字符串和要查找的字符作为参数。它将字符串拆分为一个字符数组,并使用一个reduce
函数来累加匹配的索引并将其作为数组返回。
const findIndices = (str, char) =>
str.split('').reduce((indices, letter, index) => {
letter === char && indices.push(index);
return indices;
}, [])
Testing:
测试:
findIndices("Hello There!", "e");
// → [1, 8, 10]
findIndices("Looking for new letters!", "o");
// → [1, 2, 9]
Here is a compact (one-line) version:
这是一个紧凑的(单行)版本:
const findIndices = (str, char) => str.split('').reduce( (indices, letter, index) => { letter === char && indices.push(index); return indices }, [] );