search
HomeWeb Front-endJS Tutorialjs regular expression replace variable method

JavaScript正则实战(会根据最近写的不断更新)

1、javascript 正则对象替换创建 和用法: /pattern/flags 先简单案例学习认识下replace能干什么

正则表达式构造函数: new RegExp("pattern"[,"flags"]); 
正则表达式替换变量函数:stringObj.replace(RegExp,replace Text);

参数说明:

pattern -- 一个正则表达式文本 
flags -- 如果存在,将是以下值: 
g: 全局匹配 
i: 忽略大小写 
gi: 以上组合

//下面的例子用来获取url的两个参数,并返回urlRewrite之前的真实Url
var reg=new RegExp("(http://www.qidian.com/BookReader/)(\\d+),(\\d+).aspx","gmi");
var url="http://www.qidian.com/BookReader/1017141,20361055.aspx";
 
//方式一,最简单常用的方式
var rep=url.replace(reg,"$1ShowBook.aspx?bookId=$2&chapterId=$3");
alert(rep);
 
//方式二 ,采用固定参数的回调函数
var rep2=url.replace(reg,function(m,p1,p2,p3){return p1+"ShowBook.aspx?bookId="+p3+"&chapterId="+p3});
alert(rep2);
 
//方式三,采用非固定参数的回调函数
var rep3=url.replace(reg,function(){var args=arguments; return args[1]+"ShowBook.aspx?bookId="+args[2]+"&chapterId="+args[3];});
alert(rep3);
 
 
//方法四
//方式四和方法三很类似, 除了返回替换后的字符串外,还可以单独获取参数
var bookId;
var chapterId;
function capText()
{
  var args=arguments; 
  bookId=args[2];
  chapterId=args[3];
  return args[1]+"ShowBook.aspx?bookId="+args[2]+"&chapterId="+args[3];
}
 
var rep4=url.replace(reg,capText);
alert(rep4);
alert(bookId);
alert(chapterId);
 
 
//使用test方法获取分组
var reg3=new RegExp("(http://www.qidian.com/BookReader/)(\\d+),(\\d+).aspx","gmi");
reg3.test("http://www.qidian.com/BookReader/1017141,20361055.aspx");
//获取三个分组
alert(RegExp.$1); 
alert(RegExp.$2);
alert(RegExp.$3);

2、 学习最常用的 test exec match search  replace  split 6个方法

1) test  检查指定的字符串是否存在
var data = “123123″;
var reCat = /123/gi;
alert(reCat.test(data));  //true
//检查字符是否存在  g 继续往下走  i 不区分大小写

2) exec 返回查询值
var data = “123123,213,12312,312,3,Cat,cat,dsfsdfs,”;
var reCat = /cat/i;
alert(reCat.exec(data));  //Cat

3)match  得到查询数组
var data = “123123,213,12312,312,3,Cat,cat,dsfsdfs,”;
var reCat = /cat/gi;
var arrMactches = data.match(reCat)
for (var i=0;i {
alert(arrMactches[i]);   //Cat  cat
}

4) search  返回搜索位置  类似于indexof
var data = “123123,213,12312,312,3,Cat,cat,dsfsdfs,”;
var reCat = /cat/gi;
alert(data.search(reCat));  //23

5) replace  替换字符  利用正则替换
var data = “123123,213,12312,312,3,Cat,cat,dsfsdfs,”;
var reCat = /cat/gi;
alert(data.replace(reCat,”libinqq”));

6)split   利用正则分割数组
var data = “123123,213,12312,312,3,Cat,cat,dsfsdfs,”;
var reCat = /\,/;
var arrdata = data.split(reCat);
for (var i = 0; i {
alert(arrdata[i]);
}
3、常用表达式收集:

"^\\d+$"  //非负整数(正整数 + 0)
"^[0-9]*[1-9][0-9]*$"  //正整数
"^((-\\d+)|(0+))$"  //非正整数(负整数 + 0)
"^-[0-9]*[1-9][0-9]*$"  //负整数
"^-?\\d+$"    //整数
"^\\d+(\\.\\d+)?$"  //非负浮点数(正浮点数 + 0)
"^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$"
//正浮点数
"^((-\\d+(\\.\\d+)?)|(0+(\\.0+)?))$"  //非正浮点数(负浮点数 + 0)
"^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$"
//负浮点数
"^(-?\\d+)(\\.\\d+)?$"  //浮点数
"^[A-Za-z]+$"  //由26个英文字母组成的字符串
"^[A-Z]+$"  //由26个英文字母的大写组成的字符串
"^[a-z]+$"  //由26个英文字母的小写组成的字符串
"^[A-Za-z0-9]+$"  //由数字和26个英文字母组成的字符串
"^\\w+$"  //由数字、26个英文字母或者下划线组成的字符串
"^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$"    //email地址
"^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$"  //url
"^[A-Za-z0-9_]*$"。

正则表达式基础知识

^ Matches an input or the beginning of a line, /^a/ matches "an A", but does not match "An a"
$ Matches an input or the end of a line, /a$/ matches "An a" , without matching "an A"
* Matches the preceding metacharacter 0 or more times, /ba*/ will match b, ba, baa, baaa
+ Matches the preceding metacharacter 1 or more times, / ba+/ will match ba, baa, baaa
? Match the preceding metacharacter 0 or 1 times, /ba?/ will match b, ba
(x) Match x and save x in a file named $1...$9 In the variable
x|y matches x or y
{n} matches exactly n times
{n,} matches n or more times
{n,m} matches n-m times
[xyz ] Character set, matches any character (or metacharacter) in this set
[^xyz] does not match any character in this set
[\b] matches a backspace Symbol
\b matches the boundary of a word
\B matches the non-boundary of a word
\cX Here, X is a control character, /\cM/ matches Ctrl-M
\d matches a Alphanumeric characters, /\d/ = /[0-9]/
\D matches a non-alphanumeric character, /\D/ = /[^0-9]/
\n matches a newline character
\r matches a carriage return character
\s matches a whitespace character, including \n,\r,\f,\t,\v, etc.
\S matches a non-whitespace character, equal to /[^\ n\f\r\t\v]/
\t Matches a tab character
\v Matches a double tab character
\w Matches a character that can form a word (alphanumeric, this is My free translation, including numbers), including underscores, such as [\w] matches the 5 in "$5.98", which is equal to [a-zA-Z0-9]
\W matches a character that cannot form a word, such as [ \W] matches the $ in "$5.98", which is equal to [^a-zA-Z0-9].


For more articles related to the js regular expression replace variable method, please pay attention to 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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

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

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version