使用 JavaScript 从字符串中删除子字符串
要从字符串中删除子字符串,请调用 replace()
方法,将子字符串和空字符串作为参数传递给它,例如 str.replace("example", "")
。 replace()
方法将返回一个新字符串,其中删除了第一次出现的提供的子字符串。
const str = 'one,one,two';
// ✅ Remove first occurrence
const removeFirst = str.replace('one', '');
console.log(removeFirst); // 👉️ ",one,two"
// ✅ Remove all occurrences
const removeAll = str.replaceAll('one', '');
console.log(removeAll); // 👉️ ",,two"
// ✅ Remove first occurrence using regex
const removeRegex = str.replace(/one/, '');
console.log(removeRegex); // 👉️ ",one,two"
// ✅ Remove all occurrences using regex
const removeRegexAll = str.replace(/one/g, '');
console.log(removeRegexAll); // 👉️ ",,two"
我们将以下 2 个参数传递给 String.replace
方法:
- 我们要在字符串中匹配的子字符串
- 第一场比赛的替补
我们想要删除子字符串,所以我们提供了一个空字符串作为替换。
replace()
方法不会改变原来的字符串,它返回一个新的字符串。 字符串在 JavaScript 中是不可变的。
如果需要从字符串中删除所有出现的子字符串,请使用 String.replaceAll
方法。
要从字符串中删除所有出现的子字符串,请对字符串调用 replaceAll()
方法,将子字符串作为第一个参数传递给它,将空字符串作为第二个参数传递给它。 replaceAll
方法将返回一个新字符串,其中所有出现的子字符串都被删除。
const str = 'one,one,two';
// ✅ Remove all occurrences
const removeAll = str.replaceAll('one', '');
console.log(removeAll); // 👉️ ",,two"
replaceAll
方法采用与 replace 方法相同的 2 个参数 - 搜索字符串和每个匹配项的替换。
请注意
,replace
和replaceAll
方法也可以与正则表达式一起使用。
如果我们没有需要删除的特定子字符串,而是需要匹配的模式,请将正则表达式作为第一个参数传递给 replace
方法。
// ✅ Remove first occurrence using regex
const removeRegex = str.replace(/[0-9]/, '');
console.log(removeRegex); // 👉️ "23,one,two"
// ✅ Remove all occurrences using regex
const removeRegexAll = str.replace(/[0-9]/g, '');
console.log(removeRegexAll); // 👉️ ",one,two"
正斜杠 //
标记正则表达式的开始和结束。
在正则表达式内部,我们有一个字符类 []
匹配 0 - 9 范围内的所有数字。
第一个示例仅匹配字符串中第一次出现的数字并将其替换为空字符串。
在第二个示例中,我们使用 g(全局)标志来匹配字符串中出现的所有数字。
如果在阅读正则表达式时需要帮助,请阅读正则表达式教程。 这是很有帮助的。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。