Home >Web Front-end >JS Tutorial >How to replace characters in a javascript string

How to replace characters in a javascript string

青灯夜游
青灯夜游Original
2021-06-29 16:27:589595browse

In JavaScript, you can use the replace() method of the String object to replace characters in the string. The syntax is "str.replace("String to be replaced", "New String")" or " str.replace(/String to be replaced/g, "new string")".

How to replace characters in a javascript string

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript string replacement characters

To replace all strings in js, you can use the following methods:

Two differences :Regular&General

str.replace("需要替换的字符串","新字符串") 
str.replace(/需要替换的字符串/g,"新字符串")

Example 1:

"yyyy-MM-dd-hh-mm-ss".replace("-","/")

The result is as follows:

"yyyy/MM-dd-hh-mm-ss"

Example 2:

"yyyy-MM-dd-hh-mm-ss".replace(/-/g,"/")

The result is as follows:

"yyyy/MM/dd/hh/mm/ss"

In summary:

Regular replacement will only replace the first matching character, regular replacement can replace all

Description: JavaScript replace() method

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

Syntax

stringObject.replace(regexp/substr,replacement)
Parameters Description
regexp/substr

Required. 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.

Return value

A new string obtained by replacing the first match or all matches of regexp with replacement.

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to replace characters in a javascript string. 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