search
HomeWeb Front-endJS TutorialUsage of JavaScript replace string replacement function

replace 
语法 stringObj.replace(rgExp, replaceText) 
stringObj  必选项。要执行该替换的 String 对象或文字。该对象不会被 replace 方法修改。 
rgExp  必选项。描述要查找的内容的一个正则表达式对象。 
replaceText  必选项。是一个String 对象或文字,对于stringObj 中每个匹配 rgExp 中的位置都用该对象所包含的文字加以替换。 
例如: 

Js代码  

<script> </script>

var strM = "javascript is a good script language";  

//在此我想将字母a替换成字母A  

alert(strM.replace("a","A"));  

  

这样只能替换第一个“a”字母  

  

<script> </script>

var strM = "javascript is a good script language";  

//在此将字母a全部替换成字母A  

alert(strM.replace(/a/g,"A"));  

  

这样可以替换所有“a”字母。其中g为全局标志  



JavaScript--正则表达式 

  正则表达式(regular expression)对象包含一个正则表达式模式(pattern)。它具有用正则表达式模式去匹配或代替一个串(string)中特定字符(或字符集合)的属性(properties)和方法(methods)。 

正则表达式构造函数: new RegExp("pattern"[,"flags"]); 
参数说明: 
pattern -- 一个正则表达式文本 
flags -- 如果存在,将是以下值: 
g: 全局匹配 
i: 忽略大小写 
gi: 以上组合 

在构造函数中,一些特殊字符需要进行转意(在特殊字符前加"\")。正则表达式中的特殊字符: 
字符  含意  
\ 转意,即通常在"\"后面的字符不按原来意义解释,如/b/匹配字符"b",当b前面加了反斜杆后/\b/,转意为 

匹配一个单词的边界。 
-或- 
对正则表达式功能字符的还原,如"*"匹配它前面元字符0次或多次,/a*/将匹配a,aa,aaa,加了"\"后,/a\*/ 

将只匹配"a*"。  
^  匹配一个输入或一行的开头,/^a/匹配"an A",而不匹配"An a"  
$  匹配一个输入或一行的结尾,/a$/匹配"An a",而不匹配"an A"  
*  匹配前面元字符0次或多次,/ba*/将匹配b,ba,baa,baaa  
+  匹配前面元字符1次或多次,/ba*/将匹配ba,baa,baaa  
?  匹配前面元字符0次或1次,/ba*/将匹配b,ba  
(x)  匹配x保存x在名为$1...$9的变量中  
x|y  匹配x或y  
{n}  精确匹配n次  
{n,}  匹配n次以上  
{n,m}  匹配n-m次  
[xyz]  字符集(character set),匹配这个集合中的任一一个字符(或元字符)  
[^xyz]  不匹配这个集合中的任何一个字符  
[\b]  匹配一个退格符 
\b  匹配一个单词的边界  
\B  匹配一个单词的非边界 
\cX  这儿,X是一个控制符,/\cM/匹配Ctrl-M  
\d  匹配一个字数字符,/\d/ = /[0-9]/  
\D  匹配一个非字数字符,/\D/ = /[^0-9]/  
\n  匹配一个换行符  
\r  匹配一个回车符  
\s  匹配一个空白字符,包括\n,\r,\f,\t,\v等  
\S  匹配一个非空白字符,等于/[^\n\f\r\t\v]/  
\t  匹配一个制表符  
\v  匹配一个重直制表符  
\w  匹配一个可以组成单词的字符(alphanumeric,这是我的意译,含数字),包括下划线,如[\w]匹配"$5.98" 

中的5,等于[a-zA-Z0-9]  
\W  匹配一个不可以组成单词的字符,如[\W]匹配"$5.98"中的$,等于[^a-zA-Z0-9]。 

说了这么多了,我们来看一些正则表达式的实际应用的例子: 
HTML代码的屏蔽 

Js代码  

function mask_HTMLCode(strInput) {   

var myReg = //;   

return strInput.replace(myReg, "<$1>");   

}

E-mail address verification:

function test_email(strEmail) {

var myReg = /^[_a-z0-9]+@([_a-z0-9]+.)+[a-z0 -9]{2,3}$/;

if(myReg.test(strEmail)) return true;

return false;

}


Properties and methods of regular expression objects:
Predefined regular expressions The expression has the following static properties: input, multiline, lastMatch, lastParen, leftContext,

rightContext and $1 to $9. Among them, input and multiline can be preset. The values ​​of other attributes are assigned different values ​​according to different conditions after executing the exec or test method. Many properties have both long and short (perl-style) names, and both names refer to the same value. (

JavaScript simulates perl’s regular expressions)

Attributes of regular expression objects:
Attribute meanings
$1...$9 If they (they) exist, they are the matched substrings
$_ See input
$* See multiline
$& See lastMatch
$+ See lastParen
$` See leftContext
$'' See rightContext
constructor Create a special function prototype of an object
global Whether to match in the entire string (bool type)
ignoreC ase When matching Whether to ignore case (bool type)
input    The matched string
lastIndex    The index of the last match
lastParen    The last substring enclosed in parentheses   
leftContext       The substring starting from the left of the most recent match   
multiline   Whether to perform multi-line matching (bool type)
prototype  Allows additional attributes to the object
rightContext  Regular expression pattern   
lastIndex  The index of the last match   Method of regular expression object:
Method meaning
compile  regular expression compare
exec   Execute a search
test   Perform a match
toSource   Return the definition of a specific object (literal

representing), whose value can be used to create a new object. Obtained by overloading the Object.toSource method.
toString   Returns the string of a specific object. Obtained by overloading the Object.toString method.
valueOf   Returns the original value of a specific object. Overload the Object.valueOf method to get


Example:


Js code

var myReg = /(w+)s(w+)/;

var str = " John Smith";

var newstr = str.replace(myReg, "$2, $1");

document.write(newstr);

will output "Smith, John"

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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use