20190713
阅读http://www.w3school.com.cn/index.html笔记
js字符串方法
1.1查找字符串中的字符串
indexOf() 方法返回字符串中指定文本首次出现的索引(位置)
var m = "Bts and family is my life you are my sunshine";
var a = m.indexOf("my")
alert(a)//结果为18
lastIndexOf() 方法返回指定文本在字符串中最后一次出现的索引
注:如果未找到文本值, indexOf() 和 lastIndexOf() 都返回 -1。
var a = m.indexOf("my",19)//值为34,从my出现第一次后的位置开始向后查找第二个my
1.2检索字符串中的字符串
search() 方法搜索特定值的字符串,并返回匹配的位置
注:search()与indexOf()的区别
search() 方法无法设置第二个开始位置参数。
indexOf() 方法无法设置更强大的搜索值(正则表达式)。
正则表达式
1.3提取部分字符串
三种方法
slice(start, end)
var m = "Bts and family is my life you are my sunshine";
var a = m.slice(8,14)//8为起始索引为family中f的位置,14为终止索引为family中y后面的一个位置
alert(a)//结果为family
slice()中的值为负数时
var m = "Bts and family is my life you are my sunshine";
var a = m.slice(-11,-9)//-11为my中m的位置,-9为my中y的后一个位置
alert(a)//结果为my
slice()中单个值
var m = "Bts and family is my life you are my sunshine";
var a = m.slice(-8)//-8为从结尾开始计数
alert(a)//结果为sunshine
var m = "Bts and family is my life you are my sunshine";
var a = m.slice(2)//2为从开始计数,第2个数后的所有值都输出(包括2),从0开始计数
alert(a)//结果为s and family is my life you are my sunshine
提示:负值位置不适用 Internet Explorer 8 及其更早版本。
substring(start, end)与slice()类似,无法接受负数
substr(start, length)与slice()类似
不同点在于
var m = "Bts and family is my life you are my sunshine";
var a = m.substr(4,3)//4为and中a的位置,3为所取字符串的长度
alert(a)//结果为and
注意:substr(start, length)中第二个参数不能为负数,他为字符串长度
1.4替换字符串内容
replace() 方法用另一个值替换在字符串中指定的值
对大小写很敏感
var m = "Bts and family is my life you are my sunshine";
var a = m.replace("family","Family")//把m中的"family"替换为"Family"
alert(a)//结果为Bts and Family is my life you are my sunshine
如需执行大小写不敏感的替换,请使用正则表达式 /i(大小写不敏感),正则表达式不带引号
var m = "Bts and family is my life you are my sunshine";
var a = m.replace(/FAMILY/i,"Family")
alert(a)//结果为Bts and Family is my life you are my sunshine
如需替换所有匹配,请使用正则表达式的g标志(用于全局搜索)
var m = "Bts and family is my life you are my sunshine";
var a = m.replace(/my/g,"OUR")
alert(a)//结果为Bts and family is OUR life you are OUR sunshine
1.5转换大小写
toUpperCase() 把字符串转换为大写
toLowerCase() 把字符串转换为小写
1.6 concat()方法
concat() 连接两个或多个字符串
1.7 trim()方法
trim()方法删除字符串两端的空白(IE8或更低版本不支持)
1.8 charAt()方法
charAt()返回字符串中指定位置的字符串
var str = "ONLY ONE";
alert(str.charAt(3));//返回Y
1.9 charCoadAt()方法
charCodeAt() 方法返回字符串中指定索引的字符 unicode 编码
var str = "ONLY ONE";
alert(str.charCodeAt(0));//返回79
1.11属性访问???
http://www.w3school.com.cn/js/js_string_methods.asp
1.12把字符串转换为数组
使用split()转换
var str = "RM,JIN,SUGA,J_HOPE,JIMIN,V,JUNGKOOK";
var one = str.split( ",");
alert(one[1]);//返回JIN