JS String对象 (length属性 方法)

String 对象描述
字符串是 JavaScript 的一种基本的数据类型。
String 对象的 length 属性声明了该字符串中的字符数。
String 类定义了大量操做字符串的方法,例如从字符串中提取字符或子串,或者检索字符或子串。
须要注意的是,JavaScript 的字符串是不可变的(immutable),String 类定义的方法都不能改变字符串的内容。像 String.toUpperCase() 这样的方法,返回的是全新的字符串,而不是修改原始字符串。
indexOf() 检索字符串。
该方法将从头至尾地检索字符串 stringObject,看它是否含有子串 searchvalue。javascript

<script type="text/javascript">
var str="Hello world!"
document.write(str.indexOf("Hello") + "<br />")
document.write(str.indexOf("World") + "<br />")
document.write(str.indexOf("world"))
</script>
0
-1
6

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

var str="Hello world!"
document.write(str.lastIndexOf("Hello") + "<br />")
document.write(str.lastIndexOf("World") + "<br />")
document.write(str.lastIndexOf("world"))
0
-1
6

replace() 替换与正则表达式匹配的子串。
一个新的字符串,是用 replacement 替换了 regexp 的第一次匹配或全部匹配以后获得的。web

var str="Visit Microsoft!"
    document.write(str.replace(/Microsoft/, "W3School"))
    结果:Visit 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.

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

var str="Hello happy world!"
document.write(str.slice(6))
输出:happy world!
var str="Hello happy world!"
document.write(str.slice(6,11))
输出:happy

substr() 方法可在字符串中抽取从 start 下标开始的指定数目的字符。app

var str="Hello world!"
document.write(str.substr(3))
输出:lo world!
var str="Hello world!"
document.write(str.substr(3,7))
输出:lo worl

substring() 方法用于提取字符串中介于两个指定下标之间的字符。
substring() 方法返回的子串包括 start 处的字符,但不包括 stop 处的字符。svg

var str="Hello world!"
document.write(str.substring(3,7))
输出:lo w

toLowerCase() 方法用于把字符串转换为小写。
stringObject.toLowerCase()
toUpperCase() 方法用于把字符串转换为大写。
stringObject.toUpperCase()