Click here to Skip to main content
15,885,985 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Using indexOf function we can find the index of particular string. How to get the index of all the occurrences of string.Is there any simplest way to do it?
Posted

Tty
string myString= "Check occurrences within this string.";
int count = myString.match(/in/g);// Search for 'in' occurrences in string
 
Share this answer
 
v4
Comments
Vidhya Raju 8-Sep-14 5:23am    
Thanks for the answer. Actually I need to select all the occurences of searched string.The following code does that except its not jumping to the location where the string is selected. Can you tell me how to do this?

<textarea type="text" id="input_tag">This is the testing</textarea>

<script>
(function() {
if (!HTMLInputElement.prototype.setSelectionRange) {
HTMLInputElement.prototype.setSelectionRange = function(start, end) {
if (this.createTextRange) {
var range = this.createTextRange();
this.collapse(true);
this.moveEnd('character', start);
this.moveStart('character', end);
this.select();
}
}
}
})();
var search="testing";
var regexp = /testing/g;
var foo = document.getElementById("input_tag").value;
var match, matches = [];

while ((match = regexp.exec(foo)) != null) {
document.getElementById("input_tag").setSelectionRange(match.index,(match.index)+(search.length));

}
</script>
Use a regex:
C#
var regex = /,/g;
var instr = "1,2,3,4";
var current;
var matchIndexes = [];

while ((current = regex.exec(instr)) != null)
{
   matchIndexes.push(current.index);
}
 
Share this answer
 
Comments
Vidhya Raju 8-Sep-14 6:47am    
var regex ="/" + "document.getElementById(id).value" + "/g";

If I parse the value to regex like above. Its not working. How to parse the variable into regex?
OriginalGriff 8-Sep-14 6:57am    
:sigh:
I think you need to go back to your notes and start again with what "var" means...
var regex = new RegExp(document.getElementById(id).value, "g");

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900