本文汇总了JavaScript中常用的字符串操作方法,包括获取指定位置字符、拼接字符串、截取子串、查找子串索引、去除首尾空格、模式匹配及替换等。通过具体代码示例展示了charAt、concat、slice、substring、indexOf、trim、match、search和replace等方法的实际用法与注意事项。
JavaScript字符串常用操作方法实例详解
本文介绍JavaScript中常用的字符串操作方法,供读者参考学习。
【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程序设计有所帮助。