js 字符串String

创建方式

String类型是字符串的对象包装类型,可以使用String构造函数创建。

var str = new String('hello world')
var str = String('hello world')
var str = 'hello world'
字符方法

charAt() 以单字符串的形式返回给定位置的那个字符
charCodeAt() 以单字符串的形式返回给定位置的那个字符编码
这两个方法都接收一个参数,即基于0的字符位置(下标)。

  var str = new String('hello world');
  console.log(str.charAt(3));//l  找下标为3的元素
  console.log(str.charCodeAt(4));//'111'找下标为4的元素的字符编码
fromCharCode() 方法。

接受一个或多个字符编码,然后将他们转换成一个字符串

  console.log(String.fromCharCode(104,101,108,108,111)); //hello

字符串操作方法

concat

用于将一个或多个字符串拼接起来,返回拼接得到的新字符串

  var str = 'hello ';
  var newstr = str.concat('world','!');
  console.log(newstr);//返回拼接后的值
  console.log(str);//不改变原字符串

*** ES还提供了三个基于子字符串创建新字符串的方法:
slice(start,end)
substring(start,end)
substr(index,howmany)

  var str = 'hello world';
  console.log(str.slice(3));//截取下标为3的后面的元素
  console.log(str.substring(3));//同上 lo world
  console.log(str.substr(3));//同上
  console.log(str.slice(3,7));//lo w  截取下标3-7之间的元素
  console.log(str.substring(3,7));//lo w
  console.log(str.substr(3,7));//lo worl 截取下标3开始后面的7个元素

在传递给这些方法的参数是负数的情况时,他们的行为就不相同了。

var str = "hello world";
console.log(str.slice(-3)); //"rld"
// console.log(str.substring(-3);//"hello world" 此方法的参数是负数都转换为0
console.log(str.substr(-3)); //"rld"
console.log(str.slice(3,-4)); //"lo w"
console.log(str.substring(3,-4)); //"hel" 此方法会将较小的数作为开始位置
console.log(str.substr(3,-4)); //""(空字符串)

字符串位置方法
    var str = "hello world";
console.log(str.indexof("o"));   //4
console.log(str.lastIndexof("o")); //7
console.log(str.indexof("o",6));  //7
console.log(str.lastIndexof("o",6)); //4
trim()方法 此方法会创建一个字符串副本,删除前置以及后缀的所有空格,然后返回结果。
var str = "  hello world   ";
var newStr = str.trim();
console.log(newStr);  //"hello world"
console.log(str);     //"  hello world   "
字符串大小写转换方法

toLowerCase() 转小写
toLocaleLowerCase() 根据特定地区的语言转小写
toUpperCase() 转大写
toLocaleUpperCase() 根据特定地区转大写

replace() 为了简化替换子字符串的操作。
split() 以指定的分隔符将一个字符串分割成多个子字符串,并将结果放在一个数组
  var colors = "red,blue,green,yellow";
  var Es = colors.split("e");
  console.log(Es);  // ["r","d,blu",",gr","","n,y","llow"]

你可能感兴趣的:(js 字符串String)