웹 프론트엔드 JS 튜토리얼 JavaScript `string.replace()` 유용한 사례

JavaScript `string.replace()` 유용한 사례

Sep 13, 2024 pm 10:16 PM

JavaScript `string.replace()` useful cases

1. Simple String Replacement

Replace the first occurrence of a substring.

let str = "Hello world!";
let result = str.replace("world", "JavaScript");

// Output: "Hello JavaScript!"
로그인 후 복사

2. Global String Replacement

Replace all occurrences of a substring, use the global (g) flag with regular expression.

let str = "Hello world, world!";
let result = str.replace(/world/g, "JavaScript");

// Output: "Hello JavaScript, JavaScript!"

로그인 후 복사

3. Case-insensitive Replacement

You can make the replacement case-insensitive using the i flag.

let str = "Hello World, World!";
let result = str.replace(/world/gi, "JavaScript")

// Output: "Hello JavaScript, JavaScript!"
로그인 후 복사

4. Replace Whole Words (Word Boundary)

Replace only whole words using \b word boundary.

let str = "This is a test word, test.";
let result = str.replace(/\btest\b/, "success");

// Output: "This is a success word, test."
로그인 후 복사

Replace all occurrences of the whole word, use the global flag.

let str = "This is a test word, test.";
let result = str.replace(/\btest\b/g, "success");

// Output: "This is a success word, success."
로그인 후 복사

5. Using a Function for Replacement

You can pass a function to replace() that dynamically generates the replacement string.

let str = "The price is $10";
let result = str.replace(/\$\d+/g, (match) => {
   return `$${parseInt(match.substring(1)) * 2}`
});

// Output: "The price is $20"
로그인 후 복사

6. Capturing Groups with Replacement

Using regular expressions, you can capture parts of the match and reuse them in the replacement string.

let str = "John Smith";
let result = str.replace(/(\w+)\s(\w+)/, "$2, $1");

// Output: "Smith, John"
로그인 후 복사

7. Escaping Special Characters

If you need to replace special characters like . or *, you need to escape them in the regular expression.

let str = "Price: 5.99";
let result = str.replace(/\./, ",");

// Output: "Price: 5,99"
로그인 후 복사

8. Replacing Non-ASCII Characters

To replace characters that aren't in the ASCII range, you can use Unicode properties.

let str = "Héllo Wörld";
let result = str.replace(/[^\x00-\x7F]/g, "");

// Output: "Hllo Wrld"
로그인 후 복사

9. Replacing Digits

You can replace digits (or groups of digits) using regular expressions.

let str = "Contact: 123-456-7890";
let result = str.replace(/\d{3}/g, "***");

// Output: "Contact: ***-***-***0"
로그인 후 복사

10. Replacing Special Characters using Unicode

You can also use Unicode escape sequences to replace special characters.

let str = "I love ☕!";
let result = str.replace(/\u2615/g, "coffee"); 

// Output: "I love coffee!"
로그인 후 복사

위 내용은 JavaScript `string.replace()` 유용한 사례의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

JavaScript로 문자열 문자를 교체하십시오 JavaScript로 문자열 문자를 교체하십시오 Mar 11, 2025 am 12:07 AM

JavaScript로 문자열 문자를 교체하십시오

jQuery 날짜가 유효한지 확인하십시오 jQuery 날짜가 유효한지 확인하십시오 Mar 01, 2025 am 08:51 AM

jQuery 날짜가 유효한지 확인하십시오

jQuery는 요소 패딩/마진을 얻습니다 jQuery는 요소 패딩/마진을 얻습니다 Mar 01, 2025 am 08:53 AM

jQuery는 요소 패딩/마진을 얻습니다

10 JQuery Accordions 탭 10 JQuery Accordions 탭 Mar 01, 2025 am 01:34 AM

10 JQuery Accordions 탭

10 JQuery 플러그인을 확인할 가치가 있습니다 10 JQuery 플러그인을 확인할 가치가 있습니다 Mar 01, 2025 am 01:29 AM

10 JQuery 플러그인을 확인할 가치가 있습니다

노드 및 HTTP 콘솔로 HTTP 디버깅 노드 및 HTTP 콘솔로 HTTP 디버깅 Mar 01, 2025 am 01:37 AM

노드 및 HTTP 콘솔로 HTTP 디버깅

jQuery div에 스크롤 바를 추가합니다 jQuery div에 스크롤 바를 추가합니다 Mar 01, 2025 am 01:30 AM

jQuery div에 스크롤 바를 추가합니다

사용자 정의 Google 검색 API 설정 자습서 사용자 정의 Google 검색 API 설정 자습서 Mar 04, 2025 am 01:06 AM

사용자 정의 Google 검색 API 설정 자습서

See all articles