Home >Web Front-end >JS Tutorial >How to delete a character in String with javascript

How to delete a character in String with javascript

coldplay.xixi
coldplay.xixiOriginal
2021-04-08 16:45:553412browse

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.

How to delete a character in String with javascript

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn