本文实例讲述了JS字符串常用操作方法。分享给大家供大家参考,具体如下:
【String类型】
1.返回给定位置的那个字符
var stringValue = \"hello world\"; alert(stringValue.charAt(1)); //\"e\" //如果你想得到是不是字符而是字符编码 var stringValue = \"hello world\"; alert(stringValue.charCodeAt(1)); //输出\"101\"
2.concat(),将一或多个字符串拼接起来,返回拼接得到的新的字符串
var stringValue = \"hello \"; var resrult = stringValue.concat(\"world\"); alert(resrult); //\"hello world\" alert(stringValue); //\"hello \"
3.返回被操作字符串的一个子字符串
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\" //返回7个字符 alert(stringValue.substring(3,7)); //\"lo worl\"
4.从一个字符串搜索指定的子字符串,返回子字符串的位置(没有找到返回-1)
var stringValue = \"hello world\"; alert(stringValue.indexOf(\"o\")); //4 alert(stringValue.lastIndexOf(\"o\")); //7
5.trim(),会创建一个字符串副本,删除前置以及后缀的所有空格[IE8及一下不支持]
var stringValue = \" hello world \"; var trimSting = stringValue.trim(); alert(trimSting); //\"hello world\" alert(stringValue); //\" hello world \"
6.字符串的模式匹配方法
var text = \"cat,bat,sat,fat\"; var pattern = /.at/; var matches = text.match(pattern); alert(matches[0]); //\"cat\"
7.search()方法,返回字符串中第一个匹配项的索引
var text = \"cat,bat,sat,fat\"; var pos = text.search(/at/); alert(pos); //1
8.替换
var text = \"cat,bat,sat,fat\"; var result = text.replace(\"at\",\"ond\"); alert(result); //\"cond,bat,sat,fat\" result = text.replace(/at/g,\"ond\"); alert(result); //\"cond,bond,sond,fond\"
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:http://tools.freexyz.cn/code/HtmlJsRun测试上述代码运行效果。
更多关于JavaScript相关内容还可查看本站专题:《JavaScript字符与字符串操作技巧总结》、《JavaScript数组操作技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript数学运算用法总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript查找算法技巧总结》及《JavaScript错误与调试技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。
© 版权声明
THE END
暂无评论内容