html tool

2017年7月26日星期三

js + 正则

替换============================================
http://www.w3school.com.cn/jsref/jsref_replace.asp
实例
例子 1
在本例中,我们将使用 "W3School" 替换字符串中的 "Microsoft":


var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School"))


输出:
Visit W3School!
例子 2
在本例中,我们将执行一次全局替换,每当 "Microsoft" 被找到,它就被替换为 "W3School":


var str="Welcome to Microsoft! "
str=str + "We are proud to announce that Microsoft has "
str=str + "one of the largest Web Developers sites in the world."

document.write(str.replace(/Microsoft/g, "W3School"))


输出:
Welcome to W3School! We are proud to announce that W3School
has one of the largest Web Developers sites in the world.




查找===========================================
http://www.w3school.com.cn/jsref/jsref_search.asp
实例
例子 1
在本例中,我们将检索 "W3School":


var str="Visit W3School!"
document.write(str.search(/W3School/))


输出:
6
在下面的例子中,无法检索到 w3school(因为 search() 对大小写敏感)。


var str="Visit W3School!"
document.write(str.search(/w3school/))


输出:
-1
例子 2
在本例中,我们将执行一次忽略大小写的检索:


var str="Visit W3School!"
document.write(str.search(/w3school/i))


输出:
6



没有评论:

发表评论