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

How to replace string in javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-04-08 16:24:5938776browse

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("需要替换的字符串","新字符串")

Regular

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

For example:

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

The results are as follows:

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

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!

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