[Javascript] InStr in JavaScript
- Posted at 2008/01/17 14:00
- Filed under 일함서/함수바리
asp에서 쓰던 mid 와 instr을 자바스크립트 함수로 만든것
Mid(string, start, length): Returns a specified number of characters from a string
IN: str - the string we are LEFTing
start - our string's starting position (0 based!!)
len - how many characters from start we want to get
RETVAL: The substring from start to start+len
Keep in mind that strings in JavaScript are zero-based, so if you ask for Mid("Hello",1,1), you will get "e", not "H". To get "H", you would simply type in Mid("Hello",0,1)
You can alter the above function so that the string is one-based. Just check to make sure start is not <= 0, alter the iEnd = start + len to
iEnd = (start - 1) + len, and in your final return statement, just return ...substring(start-1,iEnd)
출처 : http://www.expertsforge.com
Mid(string, start, length): Returns a specified number of characters from a string
IN: str - the string we are LEFTing
start - our string's starting position (0 based!!)
len - how many characters from start we want to get
RETVAL: The substring from start to start+len
<script language="JavaScript">
function Mid(str, start, len)
{
// Make sure start and len are within proper bounds
if (start < 0 || len < 0) return "";
var iEnd, iLen = String(str).length;
if (start + len > iLen)
iEnd = iLen;
else
iEnd = start + len;
return String(str).substring(start,iEnd);
}
</script>
You can alter the above function so that the string is one-based. Just check to make sure start is not <= 0, alter the iEnd = start + len to
iEnd = (start - 1) + len, and in your final return statement, just return ...substring(start-1,iEnd)
InStr(str, SearchForStr): Returns the location a character (charSearchFor) was found in the string str
InStr function written by: Steve Bamelis
InStr(strSearch, charSearchFor) : Returns the first location a substring (charSearchFor) found in the string strSearch. (If the character is not found, -1 is returned.)
Example:
alert(InStr("Hello_World", "_"))
Output:
5
InStr function written by: Steve Bamelis
InStr(strSearch, charSearchFor) : Returns the first location a substring (charSearchFor) found in the string strSearch. (If the character is not found, -1 is returned.)
<script language="JavaScript">
function InStr(strSearch, charSearchFor)
{
for (i=0; i < strSearch.length; i++)
{
if (charSearchFor == Mid(strSearch, i, 1))
{
return i;
}
}
return -1;
}
</script>
Example:
alert(InStr("Hello_World", "_"))
Output:
5
출처 : http://www.expertsforge.com
Posted by web20korea
- Tag
- InStr




,
mid



,
자바스크립트 함수



,
포함된문자열 찾기




- Response
- No Trackback , 2 Comments


