function htmlEscape(text){
return text.replace(/[<>"&]/g,function(match,pos,originalText){
switch(match){
case '<':
return '<';
case '>':
return '>';
case '&':
return '&';
case '\"':
return '"';
}
});
}
console.log(htmlEscape('<p class=\"greeting\">Hello world!</p>'));
//<p class=" greeting">Hello world!</p>
console.log(htmlEscape('<p>Hello world!</p>'));
//同上
split()
这个方法可以基于指定的分隔符将一个字符串分割成多个字符串,并将结果放在一个数组中,分隔符可以是字符串,也可以是一个RegExp。该方法可以接受第二个参数(可选)用于指定数组的大小,如果第二个参数为0-array.length范围内的值时按照指定参数输出,其他情况将所有结果都输出
[注意]IE8-对split()中的正则表达式,会忽略捕获组
[tips]如果是split(''),则原来的数组会一个字符字符分割后传出来
var colorText = 'red,blue,green,yellow';
console.log(colorText.split(''));//["r", "e", "d", ",", "b", "l", "u", "e", ",", "g", "r", "e", "e", "n", ",", "y", "e", "l", "l", "o", "w"]
console.log(colorText.split(','));//["red", "blue", "green", "yellow"]
console.log(colorText.split(',',2));//["red", "blue"]
console.log(colorText.split(/\,/));//["red", "blue", "green", "yellow"]
console.log(colorText.split(/e/));//["r", "d,blu", ",gr", "", "n,y", "llow"]
console.log(colorText.split(/[^\,]+/));//将除去逗号以外的字符串变为分隔符["", ",", ",", ",", ""],IE8-会识别为[",",",",","]
trim()(ECMAScript5)
返回删除前置及后缀空格的字符串副本
var string = ' hello world ';
console.log(string.trim());//'hello world';
[tips1]可以用trim()来判断输入的字符是否为空
if(usename.trim().length){
alert('correct');
}else{
alert('error');
}
[tips2]用正则模拟trim()
function fnTrim(str){
return str.replace(/^\s+|\s+$/,'')
}
console.log(fnTrim(' hello world '));//'hello world'