참조: MDN_replace()

var newStr = str.replace(regexp|substr, newSubstr|function)

replace는 3가지로 생각하면 쉽다.

  1. 변경할 문자열
  2. 변경할 대상 문자열 또는 regexp
  3. 변경될 대상 문자열 또는 함수(반환 값이 변경될 대상 문자열)

Untitled

인수의 정확한 수는 첫 번째 인수가 RegExp 객체인지 아닌지에 따라 다르며, 소괄호로 묶이는 부분표현식의 갯수에 따라 달라집니다.

예제)

function replacer(match, p1, p2, p3, index, string) {
  // p1: is nondigits, p2: digits, and p3: non-alphanumerics
  return [p1, p2, p3].join(' - ');
}

let newString = 'abc12345#$*%'.replace(/([^\\d]*)(\\d*)([^\\w]*)/, replacer);
console.log(newString);  // abc - 12345 - #$*%
// ([^\\d]*) -> p1
// (\\d*) -> p2
// ([^\\w]*) -> p3

다른예제)

function format(str, rep) {
  return str.replace(/\\{(\\d+)\\}/g, () => {
    return rep;
  });
}

let clickCount = 0;
function showClickCount() {
  clickCount++;
  let msg = format( '버튼의 클릭 횟수는 {0}회 입니다.', clickCount );
  console.log( msg );
}

showClickCount();
// 버튼의 클릭 횟수는 1회 입니다.