在做字符串处理的时候,我们经常需要删除字符串中的某些字符、数字、标点符号等。本文将从多个方面对删除字符串做详细的阐述,包括删除字符串中指定的字符、删除字符串中标签、删除字符串中的空格、删除字符串指定位置字符、删除字符串中的字母、删除字符串里面的数字、删除字符串中指定的字母、删除字符串中的数字、删除字符串中所有大写字母以及删除字符串中的标点符号。
一、删除字符串中指定的字符
我们可以使用replace()
方法删除字符串中指定的字符。
let str = "I love coding!";
let newStr = str.replace("o", "");
console.log(newStr); // "I lve cding!"
上面的代码中,我们将字符串中的字母"o"
删除了。
如果想要删除所有的该字符,可以使用正则表达式。
let str = "I love cooking!";
let newStr = str.replace(/o/g, "");
console.log(newStr); // "I lve cking!"
上面的代码中,我们使用了正则表达式/o/g
来删除所有的字符"o"
。
二、删除字符串中标签
使用正则表达式可以方便地删除字符串中的标签。
let str = "<p>Hello, World!</p>";
let newStr = str.replace(/<[^>]+>/g, "");
console.log(newStr); // "Hello, World!"
上面的代码中,我们使用了正则表达式/<[^>]+>/g
来删除字符串中所有的标签,包括标签。
三、删除字符串中的空格
使用replace()
方法和正则表达式可以删除字符串中的空格。
let str = " Hello, World! ";
let newStr = str.replace(/\s/g, "");
console.log(newStr); // "Hello,World!"
上面的代码中,我们使用了正则表达式/\s/g
来删除字符串中的空格。
四、删除字符串指定位置字符
我们可以使用字符串的substring()
方法或slice()
方法删除字符串中指定位置的字符。
let str = "Hello, World!";
let newStr1 = str.substring(0, 5) + str.substring(6);
console.log(newStr1); // "Hello World!"
let newStr2 = str.slice(0, 5) + str.slice(6);
console.log(newStr2); // "Hello World!"
上面的代码中,我们分别使用了substring()
方法和slice()
方法将字符串中的第6个字符","
删除了。
五、删除字符串中的字母
使用正则表达式可以删除字符串中的字母。
let str = "Hello, World!";
let newStr = str.replace(/[a-zA-Z]/g, "");
console.log(newStr); // ", !"
上面的代码中,我们使用了正则表达式/[a-zA-Z]/g
来删除字符串中的字母。
六、删除字符串里面的数字
使用正则表达式可以删除字符串中的数字。
let str = "Hello, 123 World!";
let newStr = str.replace(/\d/g, "");
console.log(newStr); // "Hello, World!"
上面的代码中,我们使用了正则表达式/\d/g
来删除字符串中的数字。
七、删除字符串中指定的字母
使用正则表达式可以删除字符串中指定的字母。
let str = "Hello, World!";
let newStr = str.replace(/l/g, "");
console.log(newStr); // "Heo, Word!"
上面的代码中,我们使用了正则表达式/l/g
来删除字符串中的字母"l"
。
八、删除字符串中的数字
使用正则表达式可以删除字符串中的数字。
let str = "Hello, 123 World!";
let newStr = str.replace(/\d/g, "");
console.log(newStr); // "Hello, World!"
上面的代码中,我们使用了正则表达式/\d/g
来删除字符串中的数字。
九、删除字符串中所有大写字母
使用正则表达式可以删除字符串中所有的大写字母。
let str = "Hello, WORLD!";
let newStr = str.replace(/[A-Z]/g, "");
console.log(newStr); // "Hello, !"
上面的代码中,我们使用了正则表达式/[A-Z]/g
来删除字符串中所有的大写字母。
十、删除字符串中的标点符号
使用正则表达式可以删除字符串中的标点符号。
let str = "Hello, World!!!";
let newStr = str.replace(/[^\w\s]|_/g, "");
console.log(newStr); // "Hello World"
上面的代码中,我们使用了正则表达式/[^\w\s]|_/g
来删除字符串中的标点符号。