Microsoft®
JScript indexOf Method |
Language Reference Version 1
|
Finds the first occurrence a substring within a String object.
strVariable.indexOf(substring, startindex)
"String Literal".indexOf(substring, startindex)The indexOf method syntax has these arguments:
Part Description substring The substring to search for within the String object. startindex An optional integer value specifying the index to begin searching within the String object. If omitted, searching begins at the beginning of the string.
The indexOf method returns an integer value indicating the beginning of the substring within the String object. If the substring is not found, a -1 is returned.You might try to use this to test if a substring is present in a string, but note that -1 is NOT false (0 is) so text.indexOf("t") is false if the first character in the string is "t" but true if the second (or following) character is "t" and it is true if "t" is not found in the string.
if ("test".indexOf("t")) {console.log("true")} undefined if ("test".indexOf("e")) {console.log("true")} true if ("test".indexOf("z")) {console.log("true")} trueEffectively, string.indexOf(substring) returns false if and only if string starts with substring. So !string.indexOf(substring) actually returns true if string starts with substring! The opposite of what you might expect.
Turns out when used with a number, the Tilde operator (bitwise not) effective does ~N => -(N+1) . This expression evaluates to 0 only when N == -1. We can leverage this by putting ~ in front of the indexOf(...) function to do a boolean check if an item exists in a String or an Array.
if (~strvar.indexOf(substring)) { //substring was found if (!~strvar.indexOf(substring)) { //substring was NOT foundIf startindex is negative, startindex is treated as zero. If it is larger than the greatest character position index, it is treated as the largest possible index.
Searching is performed from left to right. Otherwise, this method is identical to lastIndexOf.
© 1997 by Microsoft Corporation. All rights reserved.
file: /Techref/inet/iis/jscript/htm/js809.htm, 4KB, , updated: 2019/9/17 18:07, local time: 2024/11/23 00:04,
3.143.235.104:LOG IN
|
©2024 These pages are served without commercial sponsorship. (No popup ads, etc...).Bandwidth abuse increases hosting cost forcing sponsorship or shutdown. This server aggressively defends against automated copying for any reason including offline viewing, duplication, etc... Please respect this requirement and DO NOT RIP THIS SITE. Questions? <A HREF="http://techref.massmind.org/techref/inet/iis/jscript/htm/js809.htm"> indexOf Method</A> |
Did you find what you needed? |
Welcome to massmind.org! |
Ashley Roll has put together a really nice little unit here. Leave off the MAX232 and keep these handy for the few times you need true RS232! |
.