How to replace characters in a javascript string

青灯夜游
Release: 2023-01-07 11:41:17
Original
9472 people have browsed it

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,"新字符串")
Copy after login

Example 1:

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

The result is as follows:

"yyyy/MM-dd-hh-mm-ss"
Copy after login

Example 2:

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

The result is as follows:

"yyyy/MM/dd/hh/mm/ss"
Copy after login

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)
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!