How to find indices of all occurrences of one string in another in JavaScript?
var str = "I learned to play the Ukulele in Lebanon."
var regex = /le/gi, result, indices = [];
while ( (result = regex.exec(str)) ) {
indices.push(result.index);
}
UPDATE
I failed to spot in the original question that the search string needs to be a variable. I've written another version to deal with this case that uses indexOf
, so you're back to where you started. As pointed out by Wrikken in the comments, to do this for the general case with regular expressions you would need to escape special regex characters, at which point I think the regex solution becomes more of a headache than it's worth.
function getIndicesOf(searchStr, str, caseSensitive) { var searchStrLen = searchStr.length; if (searchStrLen == 0) { return []; } var startIndex = 0, index, indices = []; if (!caseSensitive) { str = str.toLowerCase(); searchStr = searchStr.toLowerCase(); } while ((index = str.indexOf(searchStr, startIndex)) > -1) { indices.push(index); startIndex = index + searchStrLen; } return indices;}
var indices = getIndicesOf("le", "I learned to play the Ukulele in Lebanon.");
document.getElementById("output").innerHTML = indices + "";
<div id="output"></div>
Get all occurrences of a substring in a very big string
Easy solution:
var str = "...";
var searchKeyword = "...";
var startingIndices = [];
var indexOccurence = str.indexOf(searchKeyword, 0);
while(indexOccurence >= 0) {
startingIndices.push(indexOccurence);
indexOccurence = str.indexOf(searchKeyword, indexOccurence + 1);
}
If you need something highly performant, you may look over specific text search/indexing algorithms like Aho–Corasick algorithm or Boyer–Moore string-search algorithm.
Really depends on your use case and if the text you're searching into is changing or is static and can be indexed beforehand for maximum performance.
Finding all indexes of a specified character within a string
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:
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 jsPerf test comparing various answers. In Safari 5.1, the IndexOf performs the best. In Chrome 19, the for loop is the fastest.
JS Match all occurrences of substring in a string
indexOf
has a fromIndex value you can use with a while loop str.indexOf(searchValue[, fromIndex])
let s = 'Hello_HaHaHaHackerRank';let find = 'HaHa'let hacker = [];let i = 0, j=0;while (~(i = s.indexOf (find,i + find.length))) hacker.push(i);console.log (hacker)
JavaScript: find all occurrences of substrings' indices in a string
Seems about right
const str = 'aabc'
const target = ['aa', 'bc']
function findOccurances(str, words) {
const list = []
str.split('').forEach((c,i) => {
words.forEach(t => {
if (str.substr(i, t.length) === t) {
list.push([i, i + t.length])
}
})
})
return list
}
console.log(findOccurances(str, target))
How to find index of all occurrences of element in array?
The .indexOf()
method has an optional second parameter that specifies the index to start searching from, so you can call it in a loop to find all instances of a particular value:
function getAllIndexes(arr, val) {
var indexes = [], i = -1;
while ((i = arr.indexOf(val, i+1)) != -1){
indexes.push(i);
}
return indexes;
}
var indexes = getAllIndexes(Cars, "Nano");
You don't really make it clear how you want to use the indexes, so my function returns them as an array (or returns an empty array if the value isn't found), but you could do something else with the individual index values inside the loop.
UPDATE: As per VisioN's comment, a simple for loop would get the same job done more efficiently, and it is easier to understand and therefore easier to maintain:
function getAllIndexes(arr, val) {
var indexes = [], i;
for(i = 0; i < arr.length; i++)
if (arr[i] === val)
indexes.push(i);
return indexes;
}
Search for all instances of a string inside a string
Try something like:
var regexp = /abc/g;
var foo = "abc1, abc2, abc3, zxy, abc4";
var match, matches = [];
while ((match = regexp.exec(foo)) != null) {
matches.push(match.index);
}
console.log(matches);
Find the indexs of all occerences a character in a string
You can try something like the following code, from this answer:
function getIndicesOf(searchStr, str, caseSensitive) {
var startIndex = 0, searchStrLen = searchStr.length;
var index, indices = [];
if (!caseSensitive) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
}
while ((index = str.indexOf(searchStr, startIndex)) > -1) {
indices.push(index);
startIndex = index + searchStrLen;
}
return indices;
}
Indexes of all occurrences of character in a string
This should print the list of positions without the -1
at the end that Peter Lawrey's solution has had.
int index = word.indexOf(guess);
while (index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index + 1);
}
It can also be done as a for
loop:
for (int index = word.indexOf(guess);
index >= 0;
index = word.indexOf(guess, index + 1))
{
System.out.println(index);
}
[Note: if guess
can be longer than a single character, then it is possible, by analyzing the guess
string, to loop through word
faster than the above loops do. The benchmark for such an approach is the Boyer-Moore algorithm. However, the conditions that would favor using such an approach do not seem to be present.]
Related Topics
JavaScript - Cannot Set Property of Undefined
How to Return Values from Async Functions Using Async-Await from Function
Can a PDF File's Print Dialog Be Opened with JavaScript
How to Check If Iframe Is Loaded or It Has a Content
Filtering Array of Objects with Arrays Based on Nested Value
How to Profile JavaScript Execution
How to Parse a Time into a Date Object from User Input in JavaScript
Are Braces Necessary in One-Line Statements in JavaScript
Scrolling an Iframe with JavaScript
JavaScript "Cannot Read Property "Bar" of Undefined
Swap Rows with Columns (Transposition) of a Matrix in JavaScript
Force Download Through Js or Query
Addition Is Not Working in JavaScript