JavaScript String 对象

本文介绍了JavaScript中常用的字符串操作方法,包括charAt(), charCodeAt(), concat(), fromCharCode(), indexOf(), lastIndexOf(), match(), replace(), slice(), split(), substring()等方法的使用示例及应用场景。

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!






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值