728x90
반응형
var newStr = str.replace(regexp|substr, newSubstr|function)
특수 교체
$$ | "$" 기호를 삽입합니다. |
$& | 매치된 문자열을 삽입합니다. |
$` | 매치된 문자열 앞쪽까지의 문자열을 삽입합니다. |
$' | 매치된 문자열 이후의 문자열을 삽입합니다. |
$n | *n*이 1이상 99이하의 정수라면, 첫번째 매개변수로 넘겨진 RegExp객체에서 소괄호로 묶인 *n*번째의 부분 표현식으로 매치된 문자열을 삽입합니다. |
매개변수가 function 일때
이 경우, 함수는 정규표현식 매치가 수행된 후 호출될 것이고, 함수의 반환값은 교체될 문자열이 된다.
만약 정규표현식의 플래그로 글로벌(g)이 오는 경우, 함수는 매치될 때마다 계속 호출됨.
function replacer(match, p1, p2, p3, offset, string)
match | 매치된 문자열. (윗쪽의 $& 표현식으로 매치된 경우와 동일합니다.) |
p1, p2, ... | 윗쪽의 $n 표현식과 동일합니다. ($1은 p1, $2는 p2...) 예를 들어, 만약 정규표현식 /(\a+)(\b+)/ 이 주어진다면p1은 \a+와 매치되고 p2는 \b+와 매치됩니다. |
offset | 조사된 전체 문자열 중에서 매치된 문자열의 index.(예를 들어, 조사될 전체 문자열이 abcd이고, 매치된 문자열이 bc면 이 매개변수의 값은 1이 됩니다.) |
string | 조사된 전체 문자열 (replace를 호출한 string) |
JavaScript regex replace() method with replacer function
The replace() method calls the replacerFunction after it finds the first match.
The replacerFunction is used to create a substring to replace the match.
If the regexp uses the global flag (g), the replace() method will call the replacerFunction after every match.
The replacerFunction has the following arguments:
- match
The matched substring. (Corresponds to $& above.) - p1, p2, …, pN
The nth string found by a capture group (including named capturing groups), provided the first argument to replace() is a RegExp object. (Corresponds to $1, $2, etc. above.) For example, if the pattern is /(\a+)(\b+)/, then p1 is the match for \a+, and p2 is the match for \b+. If the group is part of a disjunction (e.g. "abc".replace(/(a)|(b)/, replacer)), the unmatched alternative will be undefined. - offset
The offset of the matched substring within the whole string being examined. For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1. - string
The whole string being examined.
String.prototype.replace() - JavaScript | MDN
replace() 메서드는 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환합니다. 그 패턴은 문자열이나 정규식(RegExp)이 될 수 있으며, 교체 문자열은 문자열이나 모든 매치에
developer.mozilla.org
728x90
반응형
'JavaScript' 카테고리의 다른 글
undefined 방지하기 (0) | 2023.02.07 |
---|---|
JavaScipt 배열에서 중복 개수 구하기 (0) | 2022.11.01 |
정렬 (0) | 2022.07.31 |
Babel과 Webpack을 이용한 개발 환경 구축 (0) | 2022.07.12 |
JavaScript $ (0) | 2022.07.12 |