JavaScript学习总结之String类型

2017-02-08  本文已影响0人  McRay

String是字符串的对象包装类型,可以使用String构造函数来创建。
** var stringObject = new String("hello world"); **

String类型的每个实例都有一个length属性,表示字符串中包含多个字符。

String类型的方法
1、字符方法
var stringValue = "hello world";
 alert(stringValue.stringValue[1]); //"e"
2、字符串操作方法
var result = "hello " + "world";
alert(result); //"hello world"
var stringVaule = "hello world";
alert(stringValue.slice(3));//"lo world"
alert(stringValue.substring(3));//"lo world"
alert(stringValue.substr(3));//"lo world"
alert(stringValue.slice(3,7));//"lo w"
alert(stringValue.substring(3,7));//"lo w"
alert(stringValue.substr(3,7));//"lo worl"
var stringVaule = "hello world";
alert(stringValue.slice(-3));//"rld"
alert(stringValue.substring(-3));//"hello world"
alert(stringValue.substr(-3));//"rld"
alert(stringValue.slice(3,-4));//"lo w"
alert(stringValue.substring(3,-4));//"hel"
alert(stringValue.substr(3,-4));//""
3、字符串位置方法
4、trim():会创建一个字符串的副本,删除前置以及后缀的所有空格,然后返回结果;
5、字符串大小写转换方法

涉及的方法有4个:toLowerCase()、toLocaleLowerCase()、toUpperCase()、toLocaleUpperCase(),其中,toLowerCase()、toUpperCase()是两个经典的方法,而toLocaleLowerCase()、toLocaleUpperCase()方法则是针对特定地区的实现。

6、字符串的模式匹配方法
var text = "cat, bat, sat, fat";
var pattern = /.at/;
var matches = text.match(pattern);
var text = "cat, bat, sat, fat";
var pos = text.search(/at/);
alert(pos); //1
var text = "cat, bat, sat, fat";
var result = text.replace("at","ond");
alert(result); // "cond, bat, sat, fat"
result = text.replace(/at/g,"ond");
alert(result); //"cond, bond, sond, fond"
var colorText = "red,blue,green,yellow";
var colors1 = colorText.split(","); //["red","blue","green","yellow"]
var colors2 = colorText.split(",",2); //["red","blue"]
var colors3 = colorText.split(/[^\,]+/); //["", ",", ",", ",", ""]
7、localeCompare()

与操作字符串有关的最后一个方法是localeCompare(),这个方法比较两个字符串,并返回下列值中的一个:

var stringValue = "yellow";
alert(stringValue.localeCompare("black")); //1
alert(stringValue.localeCompare("yellow")); //0
alert(stringValue.localeCompare("zoo")); //-1
上一篇 下一篇

猜你喜欢

热点阅读