字符串 常用方法

1.  concat();

  可以把多个参数到指定字符串的尾部

var a="Hello"; var b="World"; 

console.log(a.concat(b)); // HelloWorld

2.  charAt();  

    charCodeAt();

    charAt();  用于返回字符串中第N个字符。  charCodeAt用于返回字符串中的第N个字符串的代码。

var a = "hello world";

console.log(a.charAt(2)); // l

console.log(a.charCodeAt(2)) // 108

3.  indexOf();

    lastIndexOf();

    都是查找字符串的位置。  indexOf()是从头开始查找。   lastIndexOf()是从尾部开始查找的。 都有俩参数,第一个参数为查找的对象,第二个参数为查找的起始位置。

var a = "hello world";

console.log(a.indexOf("lo",1)); // 3

console.log(a.indexOf(2)); // -1

4.   substr();

     substring();

     substr(start,end);  根据指定的长度来截取字符串。  第一个参数为截取字符串的起始下标,第二个参数为表示截取的长度。

var a = "hello world";

console.log(a.substr(0,5));// hello

     substring(start,stop);   start 参数字符串开始的位置,stop字符串结束的位置。

var a = "hello world";

console.log(a.substring(2,5)); // llo

5.   slice();

    slice()与substring() 类似,都是根据起始下标与结束下标来截取子字符串。

var a = "hello world";

console.log(a.slice(2,5)); // llo

slice()方法与substring()方法的区别:

区别1:如果第一个参数的值比第二个参数的值大,即起始下标大于结束下标,substring()方法能够在执行截取之前,先交换2个参数,而slice()方法无效,返回空字符串。

var a = "hello world";

console.log(a.substring(11,6)); // world

console.log(a.slice(11,6)); // 返回空

区别2: 如果参数值为负数,slice()方法能够把负号解释为从右侧开始定位,右侧第一个为-1,第二个为-2,以此类推。而substring()方法无效,并返回空字符串。

var a="Hello World";

console.log(a.substring(-5,-1)); // 空

console.log(a.slice(-5,-1)); // worl

6.  replace();

     replace(regexp,replacement); 第一个参数表示执行匹配的正则表达式,也可以是字符串;第二个参数表示准备代替匹配的子字符串。

var a = "hello a";

console.log(a.replace(/a/g,'world')) // hello world

7.  toLowerCase();

    toUpperCase();

    toLowerCase() 将字符串转换成为小写.   toUpperCase() 将字符串转换成为大写.

var a="Hello World" 

console.log(a.toLowerCase()); // hello world

console.log(a.toUpperCase()); // HELLO WORLD

 

 

 

摘自网络

posted @ 2015-04-28 14:05  范小武  阅读(151)  评论(0编辑  收藏  举报