[Javascript] InStr in JavaScript

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

<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>

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)



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.)
                                       
<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
크리에이티브 커먼즈 라이센스
Creative Commons License
이 글의 관련글
    이글의 태그와 관련된 글이 없습니다.

Posted by web20korea

2008/01/17 14:00 2008/01/17 14:00

Trackback URL : http://web20korea.com/trackback/63

Comments List

  1. OpenID Logo 행복개발자 2008/07/29 12:54 # M/D Reply Permalink

    instr 함수는 굳이 만들필요가 없을 텐데 ^^;;

    "Hello_World".indexOf("_";)

    하면 된다. ^^

    1. web20korea 2008/07/29 12:57 # M/D Permalink

      음...+_= 네 ㅋㅋㅋㅋ

Leave a comment
[로그인][오픈아이디란?]
« Previous : 1 : ... 150 : 151 : 152 : 153 : 154 : 155 : 156 : 157 : 158 : ... 212 : Next »

블로그 이미지

web20korea's

- web20korea

Site Stats

Total hits:
53624
Today:
152
Yesterday:
213