美文网首页
js截取字符串总结

js截取字符串总结

作者: vonson | 来源:发表于2020-01-09 17:49 被阅读0次

方法罗列:substr, substring, split, replace, 正则表达式;

substring

*语法*
substring(start:num end?:number)
*举例*
let aaa = 'abcdefghijklmn'
console.log(aaa.substring(2))   //cdefghijklmn
console.log(aaa.substring(2,5))   //cde

substr

*语法*
substr(from:num length?:number)
*举例*
let aaa = 'abcdefghijklmn'
console.log(aaa.substring(2))   //cdefghijklmn
console.log(aaa.substring(2,5))   //cdefg

split--使用字符串分割函数

*语法*
stringObject.split(separator,howmany)
*举例*
let str="hello world!"
let items=str.split("ll")
console.log(items)  // ["he", "oWorld!"]
取items[0] items[1]进行使用

replace

*语法*
stringObject.replace(regexp/substr,replacement)
*举例*
let abc = ',a,b,c,'
console.log(abc.replace(",", ''))  //a,b,c,
console.log(abc.replace(/,/, ''))  //a,b,c,
console.log(abc.replace(/,/g, ''))  //abc

正则表达式

*语法*
[基础语法](https://www.runoob.com/regexp/regexp-syntax.html)
修饰符:
i   执行对大小写不敏感的匹配。
g   执行全局匹配(查找所有匹配而非在找到第一个匹配后停止)。
m   执行多行匹配。
表达式:
/   /  --斜杠之间的内容
^匹配首
$匹配尾 
*举例*
let abc = ',a,b,c,'
let abcCopy = ',a,b,c, '
let reg = /,$/g;
let reg2 = /^,/g;
let reg3 = /,/g;
let reg4 = /,\s$/g;
console.log(abc.replace(reg, ''))  //,a,b,c
console.log(abc.replace(reg2, ''))  //a,b,c,
console.log(abc.replace(reg3, ''))  //abc
console.log(abc.replace(reg4, ''))  //,a,b,c,
console.log(abcCopy.replace(reg4, '')) //,a,b,c

应用场景

1.截取url中?后的参数

let str = 'https://www.abc.com/cloudLibraryDetails?detailsid=maYSGZBQf'
let items=str.split("?")
console.log(items[1])  // detailsid=maYSGZBQf
*备注*
1.现在这种方式显示参数的网站比较少;
2.存在多参数的时候截取比较麻烦;

2.去掉尾部指定字符串

let where= 'name=re=张三 and age=re=28 and sex=re=male and '
*问题*
此字符串是遍历拼接得到的,每个参数后面都有一个' and '字符串,现需要去掉末尾的;
*解决方案*
1.substring() + length
console.log(where.substring(0, where.length-5))  
2.substring()  + lastIndexOf()
console.log(where.substring(0, where.lastIndexOf(' and ')))
扩展:indexOf对应首次出现位置;
3.replace + 正则
let reg = / and $/gi;
let reg1 = /\s+and+\s$/gi;
console.log(where.replace(reg, ''))

遗留问题

在应用场景2中,'and'是作为参数传过来的情况,正则加变量问题...

相关文章

网友评论

      本文标题:js截取字符串总结

      本文链接:https://www.haomeiwen.com/subject/skxuactx.html