现在的位置: 首页 > 综合 > 正文

JavaScript String 对象及扩展

2014年02月28日 ⁄ 综合 ⁄ 共 2500字 ⁄ 字号 评论关闭

字符串是 JavaScript 的一种基本的数据类型。

String 对象的 length 属性声明了该字符串中的字符数。String 类定义了大量操作字符串的方法。

需要注意的是,JavaScript 的字符串是不可变的,String 类定义的方法都不能改变字符串的内容。

 

String 对象的方法

FF: Firefox, N: Netscape, IE: Internet Explorer

方法 描述 FF N IE
anchor() 创建 HTML 锚。 1 2 3
big() 用大号字体显示字符串。 1 2 3
blink() 显示闪动字符串。 1 2  
bold() 使用粗体显示字符串。 1 2 3
charAt() 返回在指定位置的字符。 1 2 3
charCodeAt() 返回在指定的位置的字符的 Unicode 编码。 1 4 4
concat() 连接字符串。 1 4 4
fixed() 以打字机文本显示字符串。 1 2 3
fontcolor() 使用指定的颜色来显示字符串。 1 2 3
fontsize() 使用指定的尺寸来显示字符串。 1 2 3
fromCharCode() 从字符编码创建一个字符串。 1 4 4
indexOf() 检索字符串。 1 2 3
italics() 使用斜体显示字符串。 1 2 3
lastIndexOf() 从后向前搜索字符串。 1 2 3
link() 将字符串显示为链接。 1 2 3
localeCompare() 用本地特定的顺序来比较两个字符串。 1 4 4
match() 找到一个或多个正在表达式的匹配。 1 4 4
replace() 替换与正则表达式匹配的子串。 1 4 4
search() 检索与正则表达式相匹配的值。 1 4 4
slice() 提取字符串的片断,并在新的字符串中返回被提取的部分。 1 4 4
small() 使用小字号来显示字符串。 1 2 3
split() 把字符串分割为字符串数组。 1 4 4
strike() 使用删除线来显示字符串。 1 2 3
sub() 把字符串显示为下标。 1 2 3
substr() 从起始索引号提取字符串中指定数目的字符。 1 4 4
substring() 提取字符串中两个指定的索引号之间的字符。 1 2 3
sup() 把字符串显示为上标。 1 2 3
toLocaleLowerCase() 把字符串转换为小写。 - - -
toLocaleUpperCase() 把字符串转换为大写。 - - -
toLowerCase() 把字符串转换为小写。 1 2 3
toUpperCase() 把字符串转换为大写。 1 2 3
toSource() 代表对象的源代码。 1 4 -
toString() 返回字符串。 - - -
valueOf() 返回某个字符串对象的原始值。 1 2 4

String 对象的属性

FF: Firefox, N: Netscape, IE: Internet Explorer

属性 描述 FF N IE
constructor 对创建该对象的函数的引用 1 4 4
length 字符串的长度 1 2 3
prototype 允许您向对象添加属性和方法 1 2 4
 
扩展方法(部分是自己写的):
//倒序
String.prototype.Reverse = function(){
    return this.split("").reverse().join("");
}
//是否包含指定字符
String.prototype.IsContains = function(str){
    return (this.indexOf(str) > -1);
}
//判断是否为空
String.prototype.IsEmpty = function(){
    return this == "";
}
//判断是否是整数
String.prototype.IsInt = function(){
    if (this == "NaN")
        return false;
    return this == parseInt(this).toString();
}
// 保留字母
String.prototype.getEn = function(){
    return this.replace(/[^A-Za-z]/g, "");
}
//获取字节长度,一个中文字符算2个字符
String.prototype.ByteLength = function(){
    return this.replace(/[^/x00-/xff]/g, "aa").length;
}
//从左截取指定长度的字串,一个中文字符算2个字符
String.prototype.left = function(n){
    return this.slice(0, n);
}
//从右截取指定长度的字串,一个中文字符算2个字符
String.prototype.right = function(n){
    return this.slice(this.length - n);
}
//获取Unicode
String.prototype.Unicode = function(){
    var tmpArr = [];
    for (var i = 0; i < this.length; i++)
        tmpArr.push("&#" + this.charCodeAt(i) + ";");
    return tmpArr.join("");
}
//指定位置插入字符串
String.prototype.Insert = function(index, str){
    return this.substring(0, index) + str + this.substr(index);
}
// 返回字符的长度,一个中文算2个
String.prototype.ChineseLength = function()
{
    return this.replace(/[^/x00-/xff]/g,"**").length;
}
// 判断字符串是否以指定的字符串结束
String.prototype.EndWith = function(str)
{
    return this.substr(this.length - str.length) == str;
}
// 判断字符串是否以指定的字符串开始
String.prototype.StartWith = function(str)
{
    return this.substr(0,str.length) == str;
}

抱歉!评论已关闭.