Hello I am using indexOf method to search if a string is present inside another string. But I want to get all the locations of where string is? Is there any method to get all the locations where the string exists?
<html>
<head>
<script type="text/javascript">
function clik()
{
var x='hit';
//document.getElementById('hideme').value ='';
document.getElementById('hideme').value += x;
alert(document.getElementById('hideme').value);
}
function getIndex()
{
var z =document.getElementById('hideme').value;
alert(z.indexOf('hit'));
}
</script>
</head>
<body>
<input type='hidden' id='hideme' value=""/>
<input type='button' id='butt1' value="click click" onClick="clik()"/>
<input type='button' id='butt2' value="clck clck" onClick="getIndex()"/>
</body>
</html>
Is there a method to get all positions?
finditer() The finditer function of the regex library can help us perform the task of finding the occurrences of the substring in the target string and the start function can return the resultant index of each of them.
Use the any() function to check if multiple strings exist in another string, e.g. if any(substring in my_str for substring in list_of_strings): . The any() function will return True if at least one of the multiple strings exists in the string.
The count() method returns the number of occurrences of a substring in the given string.
The find() string method is built into Python's standard library. It takes a substring as input and finds its index - that is, the position of the substring inside the string you call the method on.
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);
Here is a working function:
function allIndexOf(str, toSearch) {
var indices = [];
for(var pos = str.indexOf(toSearch); pos !== -1; pos = str.indexOf(toSearch, pos + 1)) {
indices.push(pos);
}
return indices;
}
Use example:
> allIndexOf('dsf dsf kfvkjvcxk dsf', 'dsf');
[0, 4, 18]
I don't know if there's a built in function to do it. You could do it in a simple loop though:
function allIndexes(lookIn, lookFor) {
var indices = new Array();
var index = 0;
var i = 0;
while(index = lookIn.indexOf(lookFor, index) > 0) {
indices[i] = index;
i++;
}
return indices;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With