Home Web Front-end JS Tutorial js regular expression replace variable method

js regular expression replace variable method

Jan 14, 2017 am 09:36 AM

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);
Copy after login

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 < arrMactches.length ; 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 < arrdata.length; 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 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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 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

jQuery Check if Date is Valid jQuery Check if Date is Valid Mar 01, 2025 am 08:51 AM

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

jQuery get element padding/margin jQuery get element padding/margin Mar 01, 2025 am 08:53 AM

This article discusses how to use jQuery to obtain and set the inner margin and margin values ​​of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values ​​can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

10 jQuery Accordions Tabs 10 jQuery Accordions Tabs Mar 01, 2025 am 01:34 AM

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

10 Worth Checking Out jQuery Plugins 10 Worth Checking Out jQuery Plugins Mar 01, 2025 am 01:29 AM

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

HTTP Debugging with Node and http-console HTTP Debugging with Node and http-console Mar 01, 2025 am 01:37 AM

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 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

jquery add scrollbar to div jquery add scrollbar to div Mar 01, 2025 am 01:30 AM

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

See all articles