本文实例讲述了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.jb51.net/code/HtmlJsRun测试上述代码运行效果。
更多关于JavaScript相关内容还可查看本站专题:《JavaScript字符与字符串操作技巧总结》、《JavaScript数组操作技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript数学运算用法总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript查找算法技巧总结》及《JavaScript错误与调试技巧总结》
希望本文所述对大家JavaScript程序设计有所帮助。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 华少翌.2005-华少翌【中唱艺能】【WAV+CUE】
- 群星《十二女声Ⅱ》[WAV/CUE/分轨][527MB]
- 大自然音乐系列《漫步在山裡》[WAV/CUE/分轨][502.8MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]
- 史依弘《史依弘交响乐京剧演唱专辑HQ》头版限量编号[WAV+CUE]
- 曼丽2020《女人三十风继续吹》HQCD[WAV+CUE]
- 曼丽2021《女人三十2雾之恋》HQCD[WAV+CUE]
- 隔壁老樊.2019-我曾【好听音乐】【FLAC分轨】
- 高林生.1993-牵挂你的人是我【白天鹅】【WAV+CUE】
- 洪卓立.2012-找个懂我的女孩(国专)【英皇娱乐】【WAV+CUE】
- 曼丽2022《女人三十3晚秋》HQCD[WAV+CUE]
- 曼丽2018《女人三十4冬天》HQCD[WAV+CUE]
- 柏菲-《好歌30年壹》限量开盘母带ORMCD[低速原抓WAV+CUE]
- 大自然音乐系列《水舞》[WAV/CUE/分轨][424.3MB]
- 大自然音乐系列《星光夜语》[WAV/CUE/分轨][453.3MB]