首頁 > web前端 > js教程 > 主體

JavaScript `string.replace()` 有用案例

DDD
發布: 2024-09-13 22:16:07
原創
964 人瀏覽過

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!