一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

web.js.字符串与正则表达式如何操作

时间:2017-05-15 编辑:简简单单 来源:一聚教程网

1.substring

 

 代码如下复制代码

varstr='abcdef'

alert(str.substring(2, 5));//cde不包括结束位置

alert(str.substring(1));//bcdef1

 

2.split

 

 代码如下复制代码

varstr='a*b*cd*ef'

alert(str.split('*'));//分割字符1

 

3.search 

 

 代码如下复制代码

varstr='acef'

alert(str.search(‘a'));//0查找字符位置

alert(str.search(‘f'));//3

 alert(str.search(‘ce'));//1

 alert(str.search(‘o'));//-1匹配失败则-1

 

正则

 

 代码如下复制代码

varre=newRegExp('b','i');//i不考虑大小写

//或者var re=/b/i;

varstr='abcdef'//将b换成B同样的结果,如果去掉i就不行了

alert(str.search(re));

 

1.match

 

 代码如下复制代码

varstr='asdf 34 656 cvs33'

varre=/\d/g;

alert(str.match(re));//3,4,6,5,6,3,3match 获取匹配的项目1

varstr='asdf 34 656 cvs33'

varre=/\d+/g;//全局匹配:g――global,+表示一次或者多次

alert(str.match(re));//34,656,33

 

2.replace

 

 代码如下复制代码

varstr='asdf 34 656 cvs33'

varre=/\d+/g;

varre2=/\d/g;

alert(str.replace(re,'*'));//asdf * * cvs*;

alert(str.replace(re2,'*'));//asdf ** *** cvs**1

 

去掉敏感词

 

 代码如下复制代码

varstr='河南 一村民 开封 哈哈'

  varre=/河南|开封/g;//去掉敏感词河南或开封

  varre1=/河南|开封/;

  alert(str.replace(re,'*'));

  alert(str.replace(re1,'*'))//没有去掉开封,自己试试结果1

 

3.[] 任意字符,范围

[abc]

例子:o[usb]t――obt、ost、out

[a-z]、[0-9]

例子:id[0-9]――id0、id5

[^a](排除a外的一切)

例子:o[^0-9]t――oat、o?t、o t

组合

[a-z0-9A-Z]

以上所述是小编给大家介绍的web.js.字符串与正则表达式操作,希望对大家有所帮助,如果大家有任何疑问欢迎各我留言,小编会及时回复大家的!

热门栏目