JavaScript String 对象

来源:互联网 发布:知乎客服电话 编辑:程序博客网 时间:2024/06/06 20:48

charAt() 方法


charAt() 方法可返回指定位置的字符

var str = "Hello world!"

document.write(str.charAt(1))

输出的是:e

charCodeAt() 方法


charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。

var str = "Hello world!"

document.write(str.charCodeAt(1))

输出的是:101

concat() 方法


concat() 方法用于连接两个或多个字符串

var str1 = "123 "

var str2 = "456!"

document.write(str1.concat(str2))

输出的是:123 456!

fromCharCode() 方法


fromCharCode() 可接受一个指定的 Unicode 值,然后返回一个字符串。

document.write(String.fromCharCode(72, 69, 76, 76, 79))

document.write(String.fromCharCode(65, 66, 67))

输出的是:HELLOABC

indexOf() 方法


indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置


var str = "Hello world!"

document.write(str.indexOf("Hello"))

document.write(str.indexOf("World"))

document.write(str.indexOf("world"))


输出的是:0-16

lastIndexOf() 方法


lastIndexOf() 方法可返回一个指定的字符串值最后出现的位置,在一个字符串中的指定位置从后向前搜索

var str="Hello world!"

document.write(str.lastIndexOf("Hello") + "<br />")

document.write(str.lastIndexOf("World") + "<br />")

document.write(str.lastIndexOf("world"))


输出的是:0
             -1
              6

match() 方法


match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。

var str = "Hello world!"

document.write(str.match("world") + "<br />")

document.write(str.match("World") + "<br />")

document.write(str.match("worlld") + "<br />")

document.write(str.match("world!"))


输出的是:world
             null
             null
             world!

replace() 方法


replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串

var str = "Visit Microsoft!"

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

输出的是:Visit W3School!


slice() 方法


slice() 方法可提取字符串的某个部分,并以新的字符串返回被提取的部分。

var str = "123 456 789!"

document.write(str.slice(6))


输出的是:6 789!

split() 方法


split() 方法用于把一个字符串分割成字符串数组

var str = "123 456 789 hhh ttt?"

document.write(str.split(" ") + "<br />")

document.write(str.split("") + "<br />")

document.write(str.split(" ", 3))

输出的是:123,456,789,hhh,ttt?
1,2,3, ,4,5,6, ,7,8,9, ,h,h,h, ,t,t,t,?
123,456,789


substring() 方法


substring() 方法用于提取字符串中介于两个指定下标之间的字符

var str = "Hello world!"

document.write(str.substring(3))

输出的是:lo world!