기존의 자바스크립트 정규식 사용법에 적을려다가 분량이 많아서 따로 뺀다.
자바스크립트 문자열 교체 함수
자바스크립트의 정규식을 이용한 문자열 교체는 기존의 문자열에 영향을 주지 않고 새로운 문자열 형태로 반환을 해준다. 이러한 기능을 수행하는 함수는 2개가 있다.
String.prototype.replace(regexp|substr, string|function)
패턴에 매칭되는 문자열을 다른 문자열로 치환해주고 이를 반환하는 메소드이다.
const regex1=new RegExp("\\w+");
const string1="asdf zxcv qwer";
const result1=string1.replace(regex1,"cat");
const result2=string1.replace("zxcv","cat");
console.log(string1); // asdf zxcv qwer
console.log(result1); // cat zxcv qwer
console.log(result2); // asdf cat qwer
정규식 뿐만 아니라 문자열을 줄 수 있다. 정규식에 global플래그를 줄 경우 매칭되는 모든 문자열을 교체한다.
const regex1=new RegExp("\\w+","g");
const string1="asdf zxcv qwer";
const result2=string1.replace(regex1,"cat");
console.log(string1); // asdf zxcv qwer
console.log(result2); // cat cat cat
String. prototype.replaceAll(regexp|substr, string|function)
패턴에 매칭되는 모든 문자열을 다른 문자열로 치환해준다. 정규식을 사용할 경우 global플래그가 필수적이다. 만약 존재하지 않을 시 TypeError
을 반환한다.
이 함수는 ES2021(ES12)에 추가되었기 때문에 브라우저 버전이나 nodejs버전에 따라 함수가 존재하지 않아 수행되지 않을 수도 있다.
const regex1=new RegExp("\\d+","g");
const string1="asdf 1234 asdf";
const result1=string1.replaceAll(regex1,"done");
const result2=string1.replaceAll("asdf","done");
console.log(string1); // asdf zxcv asdf
console.log(result1); // asdf done asdf
console.log(result2); // done 1234 done
만약 ES2021을 지원하지 않은 엔진을 사용 할 시 다음과 같은 에러가 발생한다.
TypeError: string1.replaceAll is not a function
String
위의 2개의 함수에서 교체될 문자열을 작성하는 string 매개변수는 기본적으로 문자열을 받는다. 이때 문자열에 $
기호를 이용하여서 복잡한 문자열을 함수 없이 용이하게 작성할 수 있다. 기호를 사용하는 방법은 다음과 같다.
-
$&
: 매칭된 문자열const regex1=new RegExp("\\d+"); const string1="asdf 1234 qwer"; const tmp=string1.match(regex1); console.log(tmp); // 1234 const result=string1.replace(regex1,"$&kkkk$&"); console.log(string1); // asdf zxcv qwer console.log(result); // asdf 1234kkkk1234 qwer
-
`$``: 매칭된 문자열의 직전까지의 문자열 전체
const regex1=new RegExp("\\d+"); const string1="asdf 1234 qwer"; const tmp=string1.match(regex1); console.log(tmp); // 1234 const result=string1.replace(regex1,"nn$`mm"); console.log(string1); // asdf zxcv qwer console.log(result); // asdf nnasdf mm qwer
매칭된 문자열인
1234
직전까지의 문자열인asdf (공백포함)
을 지칭하여서 교체된다. -
$'
: 매칭된 문자열 직후의 모든 문자열const regex1=new RegExp("\\d+"); const string1="asdf 1234 qwer"; const tmp=string1.match(regex1); console.log(tmp); // 1234 const result=string1.replace(regex1,"A$'A"); console.log(string1); // asdf zxcv qwer console.log(result); // asdf A qwerA qwer
매칭된 문자열인
1234
직후의(공백포함) qwer
문자열이 지칭하여서 교체된다. -
$n
(1≤n≤99): 정규식의 서브패턴을 기준으로 최대 99개까지 사용이 가능하며 정규식에 매칭된 문자열들에서 서브패턴에 매칭된 문자열const regex1=new RegExp("(\\w+) (\\d+) (\\w+)"); const string1="asdf 1234 qwer"; const result=string1.replace(regex1,"$3 $1 $2"); console.log(string1); // asdf zxcv qwer console.log(result); // qwer asdf 1234
정규식의 서브패턴이 3개이고 각 패턴은
asdf
,1234
,qwer
을 매칭한다. 이를 오른쪽으로 1칸씩 옮긴 문자열로 교체한 코드이다. -
$<Name>
: named capturing group을 지원하는 브라우저에서 사용 가능하다. 서브패턴에 이름을 주어 사용할 경우 이름을 통해 서브패턴의 결과를 불러온다.const regex1=new RegExp("(?<word1>\\w+) (?<word2>\\d+) (?<word3>\\w+)"); const string1="asdf 1234 qwer"; const result=string1.replace(regex1,"$<word3> $<word1> $<word2>"); console.log(string1); // asdf zxcv qwer console.log(result); // qwer asdf 1234
$n
을 설명하는 코드와 동일한 로직을 수행하지만 차이점은 정규식에?<NAME>
을 이용하여 서브패턴에 이름을 명칭하고 이를 이용하여 replace에 사용하였다는 것이다.
function
교체될 문자열이 특정 패턴이 존재한다면 이를 위한 함수를 작성할 수 있다. 함수를 이용한 방법은 다음과 같다.
const regex1=new RegExp("(\\w+) (?<number>\\d+)");
const string1="asdf 1234 qwer";
const func=(match,p1,p2,offset,string,groups)=>{
console.log(match); // asdf 1234
console.log(p1); // asdf
console.log(p2); // 1234
console.log(offset);// 0
console.log(string);// asdf 1234 qwer
console.log(groups);// { number: '1234' }
return match.concat(offset);
}
const result1=string1.replace(regex1,func);
console.log(result1); // asdf 12340 qwer
함수의 매개변수는 다음과 같다.
match
: 매칭된 문자열p1,p2,p3...
: 서브패턴에 매칭된 문자열offset
: 매칭된 문자열의 오프셋string
: 전체 문자열groups
: 브라우저가 named capturing group을 지원할 때 사용할 수 있으며 네이밍된 서브패턴에 매칭된 결과
'javascript' 카테고리의 다른 글
javascript this binding (0) | 2021.10.28 |
---|