indexOf()和replace()用法

1:indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
该方法将从头到尾地检索字符串 stringObject,看它是否含有子串 


searchvalue
在本例中,我们将在 "Hello world!" 字符串内进行不同的检索:
var str="Hello world!"
document.write(str.indexOf("Hello") + "
")
document.write(str.indexOf("World") + "
")
document.write(str.indexOf("world"))
以上代码的输出:
0
-1
6






2:replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个


与正则表达式匹配的子串。字符串 stringObject 的 replace() 方法执行的


是查找并替换的操作。它将在 stringObject 中查找与 regexp 相匹配的子


字符串,然后用 replacement 来替换这些子串
在本例中,我们将执行一次全局替换,每当 "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.

你可能感兴趣的:(indexOf()和replace()用法)