trim( )方法 删除前置及后缀的所有空格 然后返回结果。
var stringValue=' hello world ';
alert(stringValue.trim()); // hello world
trimLeft( ) 删除字符串开头空格 trimRight( ) 删除字符串末尾空格
字符串大小写转换方法
ECMAScript中涉及大小写转换的方法有4个:toLowerCase( ), toLocaleLowerCase( ),toUpperCase( )和 toLocaleUpperCase( )。
var stringValue = 'hello world';
alert(stringValue.toLocaleUpperCase()); //HELLO WORLD
alert(stringValue.toUpperCase()); //HELLO WORLD
alert(stringValue.toLocaleLowerCase()); //hello world
alert(stringValue.toLowerCase());//hello world
字符串操作方法
concat( )方法。用于讲一个或多个字符串拼接起来,返回拼接得到的新字符串。
var stringValue='hello';
var result = stringValue.concat('world');
alert(result); //helloworld
alert(stringValue); //hello
slice( ) substr( ) substring( )
var stringValue='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
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)); // ''
字符串位置方法
indexOf( ) lastIndexOf( )
var stringValue='hello world';
alert(stringValue.indexOf('o')); //4
alert(stringValue.lastIndexOf('o')); //7
alert(stringValue.indexOf('o',6)); //7 第二个参数是从第几个位置开始搜索。
alert(stringValue.lastIndexOf('o',6)); //4
replace( )
var text = 'cat,bat,sat,fat';
var result = text.replace('at','ond');
alert(result); //cond,bat,sat,fat // 替换字符串'at'第一次出现的位置。
result= text.replace(/at/g,'ond');
alert(result); //cond,bond,sond,fond // 通过带有全局标记的正则表达式,将全的'at'替换为'ond'
split( )方法可以基于指定的分隔符将一个字符串分割成多个子字符串,并将其放到一个数组中。
var colors = "red,blue,red,purple,orange";
console.log(colors.split(",")); //["red", "blue", "red", "purple", "orange"]
console.log(colors.split(",",2)); //["red", "blue"] 第二个参数指定数组的大小。