Timeline for JavaScript: String.indexOf(...) allowing regular-expressions?
Current License: CC BY-SA 3.0
8 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Oct 28, 2021 at 14:07 | comment | added | Stan Sokolov | this code will not work if i is undefined (it is optional). So a bit more fool proof version with input check: regexIndexOf(text, re, i) { let idx = (i && i > 0) ? text.substr(i).search(re) : text.search(re); return idx < 0 ? idx : idx + (i?i:0); } | |
| Feb 11, 2017 at 8:20 | history | edited | Web_Designer | CC BY-SA 3.0 | add regexp arg to function |
| Aug 10, 2014 at 22:11 | comment | added | gkoberger | Great solution, however the output is a bit different. indexOf will return a number from the beginning (regardless of the offset), whereas this will return the position from the offset. So, for parity, you'll want something more like this: function regexIndexOf(text, offset) { var initial = text.substr(offset).search(/re/); if(initial >= 0) { initial += offset; } return initial; } | |
| Jul 17, 2013 at 19:31 | history | edited | Fabrício Matté | CC BY-SA 3.0 | added 37 characters in body |
| May 27, 2012 at 20:40 | history | edited | Jashwant | CC BY-SA 3.0 | added 126 characters in body |
| Nov 8, 2008 at 3:01 | comment | added | Glenn | str.substr(i).search(/re/) | |
| Nov 7, 2008 at 22:17 | comment | added | Pat | from the question: While String.search() takes a regexp as a parameter it does not allow me to specify a second argument! | |
| Nov 7, 2008 at 22:11 | history | answered | Glenn | CC BY-SA 2.5 |