JS中字符串的常见属性及方法

属性

length

var txt = "abc 123";
console.log(txt.length);  // 7

方法

indexOf():返回某个指定的字符串值在字符串中首次出现的位置。

var str="abc efg, aaa";
var n=str.indexOf("aaa");  
console.log(n)  //9

trim():去除字符串的头尾空格,该方法不会改变原始字符串。

var str = "  Runoob  ";
console.log("aaa" + str + "ccc")  //aaa  Runoob  ccc
console.log("aaa" + str.trim() + "ccc");  //aaaRunoobccc

trim() 方法在使用上有浏览器限制,如果浏览器不支持,可以使用正则表达式来实现

function myTrim(x) {
  return x.replace(/^\s+|\s+$/gm,'');
}
var str = myTrim(" Runoob ");
console.log("aaa" + str + "ccc");  //aaaRunoobccc

猜你喜欢

转载自www.cnblogs.com/wenxuehai/p/10322031.html