使用 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(全局)标志来匹配字符串中出现的所有数字。
如果在阅读正则表达式时需要帮助,请阅读正则表达式教程。 这是很有帮助的。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。