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

How to replace all strings in javascript

青灯夜游
Release: 2021-09-07 13:02:22
Original
7735 people have browsed it

In JavaScript, you can use the replace() method to replace all strings. This method can replace some characters with other characters in the string. The syntax format is "string.replace("original string ","replacement value")".

How to replace all strings in javascript

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

javascript replace() method

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

Syntax format:

string.replace(searchvalue,newvalue)
Copy after login
  • searchvalue: 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 literal pattern rather than first being converted to a RegExp object.

  • #newvalue: required. A string value. Specifies functions for replacing text or generating replacement text.

The second parameter of the replace() method can use a function. When matching, the function will be called. The return value of the function will be used as the replacement text. At the same time, the function can receive $ A prefix of special characters used to reference information related to the matched text.

Special characters in the second parameter of the replace() method
Conventional stringDescription
$1, $2, ..., $99Text matching the 1st to 99th subexpressions in the regular expression
$& (Dollar sign hyphen) Substring matching the regular expression
$' (Dollar sign toggle skill key) is located Matches the text on the left side of the substring
$' (dollar sign single quote) Matches the text on the right side of the string
$$ represents $ string

Return value: a new string, which is the first time that regexp is replaced with replacement obtained after a match or all matches.

Example: replace() method replaces all strings

var str="hello";
var a=str.replace("hello","HI");
console.log(a);
Copy after login

How to replace all strings in javascript

[Recommended learning: javascript advanced tutorial

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