在做字元串處理的時候,我們經常需要刪除字元串中的某些字元、數字、標點符號等。本文將從多個方面對刪除字元串做詳細的闡述,包括刪除字元串中指定的字元、刪除字元串中標籤、刪除字元串中的空格、刪除字元串指定位置字元、刪除字元串中的字母、刪除字元串裡面的數字、刪除字元串中指定的字母、刪除字元串中的數字、刪除字元串中所有大寫字母以及刪除字元串中的標點符號。
一、刪除字元串中指定的字元
我們可以使用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!"
上面的代碼中,我們使用了正則表達式/g來刪除所有的字元”o”。
二、刪除字元串中標籤
使用正則表達式可以方便地刪除字元串中的標籤。
let str = "Hello, World!
";
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來刪除字元串中的標點符號。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/190017.html