regex - How to find indices of all occurrences of one string in another in JavaScript? -
I am trying to find the status of all versions of a string, case-insensitive.
For example, the string has been given:
I learned to play UKeye in Lebanon.
and the search string le
, I want to get the array: <2 p>
[2, 25, 27, 33]
< / Pre>will be both string variables - that is, I can not hard-code their values
I thought it was an easy task for regular expression, but after struggling to do some work, I had no luck.
How do I complete this using the
.indexOf ()
, but should definitely be a more concise way to do this?
var str = "I learned to play guitar in Lebanon." Var regex = / le / Gi, results, index = []; While ((result = regex.exec (str))) {indices.push (result.index); } UPDATE I failed to find out in the original question that the search string needs to be a variable. There is another version written in order to deal with the case, which uses indexOf
, so you have come back to where it started, as in the comments Vkkarn has told, with normal things To do this, with regular expression you should avoid special reggae characters. Require, which I think Rijksmuseum and Municipal solutions becomes more of a headache than his head.
function getIndicesOf (searchStr, str, caseSensitive) {var searchStrLen = searchStr.length; If (Search Catalin == 0) {return []; } Var startIndex = 0, index, index = []; If (! Case sensitive) {str = str.toLowerCase (); SearchStr = searchStr.toLowerCase (); } While ((index = str.indexOf (searchStr, startIndex) gt; -1) {indices.push (index); StartIndex = Pointer + Search STLN; } Return index; } Var index = getIndicesOf ("take", "I learned to play guitar in Lebanon."); Document.getElementById ("Output"). InnerHTML = Index + "";
& lt; Div id = "output" & gt; & Lt; / Div & gt;
Comments
Post a Comment