首页   /   JS,DOM   /   js中字符串的操作

内容

哈哈,为免忘记,记录如下

                     

var str = '{"Name":"WangXiaoEr","Age":"23"}';

console.log("----------------------------------从字符串中解析出json对象");
console.log(   JSON.parse(str)   );

console.log("----------------------------------从对象解析出字符串");
console.log(   JSON.stringify(JSON.parse(str))   );

console.log("----------------------------------拆分字串");
var strs= str.split(",");
console.log(   strs   );console.log(   strs.length   );

console.log("----------------------------------转换大小写");
console.log(   str.toUpperCase()   );
console.log(   str.toLowerCase()   );

console.log("----------------------------------查找");
console.log(   str.indexOf('Name')      );
console.log(   str.indexOf('Name',3)    );  // 从第3位开始查找
console.log(   str.indexOf('ddddd')     );

console.log("----------------------------------拼字符串");
var str = "aaaa"
console.log(   str.concat(" bbbb"," cccc"," dddd")      );

console.log("----------------------------------取出字串  slice");
var str = "hello world!";
console.log(   str.slice(0,2)       );//返回 lo w
console.log(   str.slice(3,7)       );//返回 lo w
console.log(   str.slice(3)         );//返回 lo world!
console.log(   str.slice(9,5)       );//返回 ""
console.log(   str.slice(-7,-3)     );//负数与长度相加,即str.slice(5,9)返回 wor
console.log(   str.slice(5,9)       );//返回

console.log("----------------------------------取出字串  substring");
// 当传入的参数是正数时,substring与slice的功能基本相同,
//      唯一的区别是当第一个参数大于第二个参数时,方法将第二个参数作为截取的起始位置而将第一个参数作为截取结束的位置,
//      且截取的字符串不包含第一个参数位置对应的值,当传入的参数是负值时,该方法会将所有的负值转化为0
console.log(   str.substring(3,7)   );//返回lo w
console.log(   str.substring(3)     );//返回lo world!
console.log(   str.substring(9,5)   );//返回 wor,即str.substring(5,9),不包含第九项
console.log(   str.substring(-7,-3) );//负数与长度相加,即str.substring(0,0)返回""
console.log(   str.substring(-7,3)  );//负数与长度相加,即str.substring(0,3)返回hel

console.log("----------------------------------取出字串  substr");
// 返回指定位置开始的指定长度的字符串,原字符串不变,
// 若第二个参数缺省就一直截取到字符串结束,当传递的参数为负值时,
//      方法会将负的第一个参数与字符串的长度相加,将负的第二个参数转化为0
console.log(   str.substr(0, 5)       );//从索引0开始,截取5个字符串,返回hello
console.log(   str.substr(7)          );//从索引7开始截取,一直到结束,返回orld!
console.log(   str.substr(-7,3)       );//负数与长度相加,即str.substr(5,3),返回 wo
console.log(   str.substr(-7,-3)      );//负数与长度相加,即str.substr(5,0),返回""

console.log("----------------------------------删除元素前置及后缀的所有空格");
// 删除元素前置及后缀的所有空格,然后返回结果,远数组不变
var str1 = "      hello world   ";
var str2 = str1.trim();
console.log(   str1                 );//返回"      hello world   "
console.log(   str2                 );//返回"hello world"



参考:http://www.cnblogs.com/lhyhappy65/p/6061143.html