본문 바로가기

WEB_Programming/Javascript

자바스크립트 정규식 사용 방법 정리

# 참고 사이트 : http://www.javascriptkit.com/javatutors/redev3.shtml

Regular Expressions methods and usage

Now, knowing how a RegExp is written is only half the game. To gain anything from them you have to know how to use them too. There are a number of ways to implement a RegExp, some through methods belonging to the String object, some through methods belonging to the RegExp object. Whether the regular expression is declared through an object constructor or a literal makes no difference as to the usage.

Description Example
RegExp.exec(string)
Applies the RegExp to the given string, and returns the match information. var match = /s(amp)le/i.exec("Sample text")

match then contains ["Sample","amp"]
RegExp.test(string)
Tests if the given string matches the Regexp, and returns true if matching, false if not. var match = /sample/.test("Sample text")

match then contains false
String.match(pattern)
Matches given string with the RegExp. With g flag returns an array containing the matches, without g flag returns just the first match or if no match is found returns null. var str = "Watch out for the rock!".match(/r?or?/g)

str then contains ["o","or","ro"]
String.search(pattern)
Matches RegExp with string and returns the index of the beginning of the match if found, -1 if not. var ndx = "Watch out for the rock!".search(/for/)

ndx then contains 10
String.replace(pattern,string)
Replaces matches with the given string, and returns the edited string. var str = "Liorean said: My name is Liorean!".replace(/Liorean/g,'Big Fat Dork')

str then contains "Big Fat Dork said: My name is Big Fat Dork!"
String.split(pattern)
Cuts a string into an array, making cuts at matches. var str = "I am confused".split(/\s/g)

str then contains ["I","am","confused"]

On that note I conclude the tutorial. Now go express yourself with JavaScript regular expressions!

'WEB_Programming > Javascript' 카테고리의 다른 글

Javascript Trim 기능 구현  (0) 2009.01.28
JQuery 기본 Selector  (0) 2009.01.25
JavaScript 습작...  (0) 2008.10.15
[JAVASCRIPT] insertBefore  (0) 2008.08.11
[HTML] 동영상 플레이 처리하기  (0) 2008.07.30