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

How to replace string in javascript

醉折花枝作酒筹
Release: 2021-04-08 16:24:59
Original
38967 people have browsed it

Methods for string replacement in js: 1. Directly use "str.replace("String to be replaced", "New String")" to replace; 2. Use regular expressions to replace, The syntax format is "str.replace(/string to be replaced/g, "new string")".

How to replace string in javascript

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

Replacement of strings in js, you can use the following method to replace all strings in js:

General

str.replace("需要替换的字符串","新字符串")
Copy after login

Regular

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

For example:

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

The results are as follows:

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

It follows that regular replacement will only replace the first matching character, while regular replacement can replace all.

Recommended learning: javascript video tutorial

The above is the detailed content of How to replace string in javascript. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template