首页 > 技术文章 > js string方法总结

tianxiaoxiao 2018-11-18 22:36 原文

.trim()方法 删除字符串前后的空格

' 123'.trim() //'123'

str.slice(beg[,end]) 方法

  • 提取字符串的一部分,并返回一个新字符串,原字符串不改变
  • end 为负数时,等价于str.length+end,去掉右侧|end|个字符
var str='hello';

console.log(str.slice(0,2)); //he 
console.log(str.slice(0,-2)); //hel 去掉右侧的两个字符

console.log(str); // hello 原字符串不变

str.replace(reg|substr,newSubStr|function)

  • 第一个参数为substr时,只替换第一个匹配项
  • /reg/ 严格匹配,只替换第一个匹配项
  • /reg/ig 忽略大小写,全局匹配,替换所有
let str ='haha xiaoxiao haha ';
let newStr1=str.replace(/haha/,'lala');
let newStr2=str.replace(/haha/ig,'lala');

console.log(newStr1) // lala xiaoxiao haha
console.log(newStr2) // lala xiaoxiao lala
console.log(str) // haha xiaoxiao haha

推荐阅读