자바스크립트 문자열 처리

Posted by 빵빵빵
2009/03/10 18:20 전산(컴퓨터)/PC-Windows



자바스크립트 문자열 처리

출처 : http://srufaculty.sru.edu/david.dailey/javascript/string.html

Some of JavaScript's
string handling mechanisms

The basics

string1.charAt(num1)
returns character at position num1 within string1

If string1 is "a string" and number is 3,
then string1.charAt(3) is "t".


number

string

string.charAt(number)
string1.indexOf(string2)
returns first character position of string2 within string1

If string1 is "a string" and substring is "str",
then string.indexOf(substring) is 2.

If string1 is "a string" and substring is "stX",
then string.indexOf(substring) is -1.


substring

string

string.indexOf(substring)
string.substring(from,to)
returns the substring within string starting at the fromth char
up to the th char

If zz is "happy" then zz.substring(3,5)="py"

 
from   to

string

string.substring(from,to)
string.length
If string="hamburger"
then string.length=9

string
string.length

Fancier stuff

string.split(re)
splits a string into an array, based on a delimiter (a string or regular expression)

If s="a.bc.def.g.hijk" and re="."
then s.split(re)[0]="a",
s.split(re)[1]="bc",
and s.split(re)[4]="hijk".

delim
  index

string

Using join and split to replace substrings (like sed 's/alpha/beta/g' in UNIX)

Using the replace method, with regular expressions:

var r=/[aeiou]/g  //a regular expression for all vowels.
var s="happy ever after in the marketplace"

Then, s.replace(r,"Q") returns "hQppy QvQr QftQr Qn the mQrkQtplQcQ"

string.match(re)
determines whether or not a string contains (matches) a given regular expression.

If string="Do it and think." and re=/[^\s]*t\s+/
then string.match(re) returns "it"
since the regular expression looks for any word ending with "t"

re= string=

string.match(re)

Dealing with keystrokes

Specialized things

eval(string)
converts string of digits (or an expression) to number
Useful for reading form elements on a page (which by default are read as strings).

if string="12345" then eval(string)=12345.
if string+1=123451,then eval(string)+1=12346.

string

eval(string)
eval(numberstring).toString(16)
converts number to hexadecimal

if numberstring=255
then numberstringtoString(16) is "ff"

number

number.toString(16)
Numeric to ASCII
number

String.fromCharCode(number)
ASCII to Numeric
ASCIIchar
 
number=ASCIIchar.charCodeAt(0)
escape(string)
replaces special characters by escape sequences

escape(string)
2009/03/10 18:20 2009/03/10 18:20

이 글에는 트랙백을 보낼 수 없습니다