Test()
문자열 사이에 영어가 있는지?(A ~ z)
- var username = 'JohnSmith';
- console.log(/[A-Za-z_-]+/.test(username)); //return true
- username = '한국인';
- console.log(/[A-Za-z_-]+/.test(username)); //return false
- username = '**A*';
- console.log(/[A-Za-z_-]+/.test(username)); //return true
Split()
문자를 띄워쓰기 기준으로 잘라 배열로 반환
- var str = 'this is my string';
- console.log(str.split(/\s/)); //logs : [this, is, my, string]
-
- str = '이건 내가 작성한 문자열';
- var str2 = str.split(/\s/);
- console.log(str2[1]); //logs : 내가
- console.log(str2[3]); //logs : 문자열
Replace()
치환 정규식
- //ex1)
- var someString = 'Hello, World';
- someString = someString.replace(/World/, 'MyBlog');
- console.log(someString); //return Hello, MyBlog
- //ex2)
- var username = 'J!o!h!n!Smith!!~';
- username = username.replace(/[^A-Za-z\d_-]+/,'');
- //처음나오는 특수문자 제거
- console.log(username); // logs : Jo!h!n!Smith!!~
- //ex3)
- var username = 'J!o!h한n !Sm글ith!!~';
- username = username.replace(/[^A-Za-z\d_-]+/g,'');
- //문자열사이 특수문자(띄어쓰기포함) 전부제거
- console.log(username); // logs : JognSmith
Match()
매치되는 특정 문자 or 문자열 반환
- var name = 'UYEONG';
- console.log(name.match(/U/)); // logs "U"
- var str = "너는착한놈이야";
- console.log(str.match(/착한놈/)) // logs "착한놈"
-
- var name = 'axaxaxsvsvsv';
- //검사하여 해당문자 배열로반환
- console.log(name.match(/a/g)) // logs ["a","a","a"]
-
- var string = 'this is just a string with some 12345 and some !#$@# meixed in.!';
- console.log(string.match(/[a-z]+/gi));
- // logs : ["this", "is", "just", "a", "string", "with", "some", "and", "some", "meixed", "in"]
- console.log(string.match(/[a-z]+/gi)[1]); // logs : is
emailAdress :
이메일을 검사한후 문자열로 반환
- var email = 'uyeong21c@gmail.com';
- console.log(email.replace(/([a-z\d_-]+)@([a-z\d_-]+)\.[a-z]{2,4}/ig, '$1, $2'));
- // logs : uyeong21c, gamil
url :
url을 구조기준으로 잘라 반환
- function loc(url) {
- return {
- search : function() {
- return url.match(/\?(.+)/i)[1];
- },
- hash : function() {
- return url.match(/#(.+)/i)[1];
- },
- protocol : function() {
- return url.match(/(ht|f)tps?:/)[0];
- },
- href : function() {
- return url.match(/(.+\.[a-z]{2,4})/ig);
- }
- }
- }
- var l = loc('http://www.somesite.com?somekey=somevalue&anotherkey=anothervalue#theHashGoesHere');
- console.log(l);
- console.log(l.search());
- console.log(l.hash());
- console.log(l.protocol());
- console.log(l.href());
출처 - UYEONG's Blog(http://uyeong.tistory.com/189)