Home >Web Front-end >JS Tutorial >How to delete a character in String with javascript
Javascript method to delete a character in String: 1. Use the [new RegExp()] method to create a regular pattern; 2. Use splitting into an array, and then re-join it into a new string.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
How to delete a certain character in String using javascript:
Method 1. Regularity
About JS deleting a character in String Character methods generally use the replace() method. However, this method will only delete once. If you need to delete all characters in the string, you must use regular expressions.
var str = "abcdaabbssaaa"; var reg = new RegExp("a","g"); var a = str.replace(reg,""); console.log(a);
The new RegExp() method is used here to create a regular expression. The first parameter "a" specifies the regular expression pattern or other regular expressions. The latter parameter is an optional string containing the attributes "g", "i", and "m", which specify global matching, case-sensitive matching, and multi-line matching respectively. Before ECMAScript was standardized, the m attribute was not supported. If pattern is a regular expression rather than a string, this parameter must be omitted.
If the result of printing reg is: /a/g.
Method 2. Separate into arrays
There is also a more tricky method, which is to divide into arrays and then re-join them into new strings.
var str = "abcdaabbssaaa"; var a = str.split("a").join(""); console.log(a);
Related free learning recommendations: javascript (video)
The above is the detailed content of How to delete a character in String with javascript. For more information, please follow other related articles on the PHP Chinese website!