var str = new String( "This is string" );
console.log("str.constructor is:" + str.constructor)
输出结果:
str.constructor is:function String() { [native code] }
length
返回字符串的长度。
var uname = new String("Hello World")
console.log("Length "+uname.length) // 输出 11
prototype
允许您向对象添加属性和方法。
function employee(id:number,name:string) {
this.id = id
this.name = name
var emp = new employee(123,"admin")
employee.prototype.email="admin@runoob.com" // 添加属性 email
console.log("员工号: "+emp.id)
console.log("员工姓名: "+emp.name)
console.log("员工邮箱: "+emp.email)
String 方法
下表列出了 String 对象支持的方法:
方法 & 描述
charAt()
返回在指定位置的字符。
var str = new String("RUNOOB");
console.log("str.charAt(0) 为:" + str.charAt(0)); // R
console.log("str.charAt(1) 为:" + str.charAt(1)); // U
console.log("str.charAt(2) 为:" + str.charAt(2)); // N
console.log("str.charAt(3) 为:" + str.charAt(3)); // O
console.log("str.charAt(4) 为:" + str.charAt(4)); // O
console.log("str.charAt(5) 为:" + str.charAt(5)); // B
var str = new String("RUNOOB");
console.log("str.charCodeAt(0) 为:" + str.charCodeAt(0)); // 82
console.log("str.charCodeAt(1) 为:" + str.charCodeAt(1)); // 85
console.log("str.charCodeAt(2) 为:" + str.charCodeAt(2)); // 78
console.log("str.charCodeAt(3) 为:" + str.charCodeAt(3)); // 79
console.log("str.charCodeAt(4) 为:" + str.charCodeAt(4)); // 79
console.log("str.charCodeAt(5) 为:" + str.charCodeAt(5)); // 66
var str1 = new String( "RUNOOB" );
var str2 = new String( "GOOGLE" );
var str3 = str1.concat( str2 );
console.log("str1 + str2 : "+str3) // RUNOOBGOOGLE
从后向前搜索字符串,并从起始位置(0)开始计算返回字符串最后出现的位置。
var str1 = new String( "This is string one and again string" );
var index = str1.lastIndexOf( "string" );
console.log("lastIndexOf 查找到的最后字符串位置 :" + index ); // 29
index = str1.lastIndexOf( "one" );
console.log("lastIndexOf 查找到的最后字符串位置 :" + index ); // 15
var str1 = new String( "This is beautiful string" );
var index = str1.localeCompare( "This is beautiful string");
console.log("localeCompare first :" + index ); // 0
var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
if (str.search(re) == -1 ) {
console.log("Does not contain Apples" );
} else {
console.log("Contains Apples" );
var str = "RUNOOB GOOGLE TAOBAO FACEBOOK";
console.log("(1,2): " + str.substring(1,2)); // U
console.log("(0,10): " + str.substring(0, 10)); // RUNOOB GOO
console.log("(5): " + str.substring(5)); // B GOOGLE TAOBAO FACEBOOK