欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

JS字符串常用操作方法实例小结

时间:2021-02-16 10:41:25|栏目:JavaScript代码|点击:

本文实例讲述了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程序设计有所帮助。

上一篇:Js参数值中含有单引号或双引号问题的解决方法

栏    目:JavaScript代码

下一篇:微信小程序从注册账号到上架(图文详解)

本文标题:JS字符串常用操作方法实例小结

本文地址:http://www.codeinn.net/misctech/63966.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有