Home >Web Front-end >Front-end Q&A >How to make replace replace all in javascript

How to make replace replace all in javascript

WBOY
WBOYOriginal
2022-01-19 16:41:5917697browse

In JavaScript, you can use "/g" in the regular expression to make replace replace all. "/g" in the regular expression means to match all. The syntax is "replacement object.replace( /Character to be replaced/g,"Replaced character ")".

How to make replace replace all in javascript

The operating environment of this tutorial: Windows 10 system, JavaScript version 1.8.5, Dell G3 computer.

javascriptHow to make replace replace all

Thereplace() method is used to replace some characters with other characters in a string, or replace A substring that matches the regular expression.

Syntax

stringObject.replace(regexp/substr,replacement)

Parameter Description

regexp/substrRequired. A RegExp object that specifies the substring or pattern to be replaced.

Note that if the value is a string, it is retrieved as a literal text pattern, rather than first being converted to a RegExp object.

replacement Required. A string value. Specifies functions for replacing text or generating replacement text.

Example:

var str = "atetateg".replace("a",""); will only replace the first a

var str = "atetateg ".replace(/a/g,""); will replace all /g represents matching the full text

In fact, we use regular expressions in JS, /\LOVE/g /\LOVE means to Find the string. What we are looking for are quotation marks. /g is the syntax of regular expressions, which means all the meaning. Here it means replacing all.

The example is as follows:

<html>
<body>
<script type="text/javascript">
var str="好好学习,田田向上。"
document.write(str.replace(/田/g,"天"))
var str="好好学习,田田向上。"
document.write(str.replace(/田/,"天"))
</script>
</body>
</html>

Output result:

How to make replace replace all in javascript

##Related recommendations:

javascript learning tutorial

The above is the detailed content of How to make replace replace all in 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