我们都知道字符串用是用单引号或双引号括起来的。在别的语言中(比如PHP),通常双引号允许转义字符,单引号则不允许转义字符。而在JavaScript中,事实上单引号和双引号的作用是完全一样的。
var s1 = "This is a \"string\"\nhaha"; var s2 = 'This is a \"string\"\nhaha';
上面例子中两个字符串完全等效。
字符串有两种形态:String Object和String Literal。
var s1 = "This is a string Literal";
var s2 = new String("This is a string object");
alert(typeof s1); // typeof(s1)=='string' , Literal
alert(typeof s2); // typeof(s1)=='object' , Object
alert(typeof s2.valueOf()); // "string", Literal
String.valueOf()回返回字符串的原始形态(Primitive Value)。
var s1 = "abc", s2 = new String("def");
function modify_it(ts1, ts2) {
ts1 += '...'; ts2 += '...';
}
modify_it(s1,s2);
alert(s1+"\n"+s2); // 字符串内容没有被改变
可见字符串是按值传递的。
下面是几种处理长字符串的方法。
// Concatenation
var s1 = 'abc '
+ 'def';
// Line Continuation
var s2 = 'abc \
def';
var s3 = "abc \
def\
";
// Array
var s4 = ['abc','def'].join(' ');
// 显示小数点后两位
number.toFixed(12345.7890); // 返回:12345.78
function commafy(num) {
var str = (num+"").split("."),
dec=str[1]||"",
num=str[0].replace(/(\d)(?=(\d{3})+\b)/g,"$1,");
return (dec) ? num+'.'+dec : num;
}
commafy(12345.7890); // 返回:12,345.7890
String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g,'');}
String.prototype.ltrim = function(){return this.replace(/^\s+/g,'');}
String.prototype.rtrim = function(){return this.replace(/\s+$/g,'');}
String.prototype.htmlEntities = function () {
return this.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
};
String.prototype.stripTags = function () {
return this.replace(/<([^>]+)>/g,'');
}