TypechoJoeTheme

至尊技术网

统计
登录
用户名
密码
/
注册
用户名
邮箱

悠悠楠杉

网站页面

js中常用的字符串函数

2020-11-20
/
0 评论
/
766 阅读
/
正在检测是否收录...
11/20

charAt() 获取某个位置上的字符

var str = "hello world, it's a nice day";
console.log(str.charAt(0));//返回h

charCodeAt() 获取某个位置上的字符的编码

var str = "hello world, it's a nice day";
console.log(str.charCodeAt(0));//返回104(l的编码)

indexOf() 从前向后查找某个字符,返回这个字符第一次出现的位置。如果没有,返回-1

var str = "hello world, it's a nice day";
console.log(str.indexOf('l'));//返回2

lastIndexOf() 从后向前查找某个字符,返回这个字符第一次出现的位置。如果没有,返回-1

var str = "hello world, it's a nice day";
console.log(str.lastIndexOf('l'));//返回9

concat() 拼接字符串,将传递的参数拼接到字符串中,不改变原字符串

var str = "hello world";
console.log(str.concat(",it's a nice day"));//返回hello world,it's a nice day

slice() 截取指定位置字符串,参数为开始位置和结束位置,不包括结束位置,不改变原字符串

var str = "hello world";
console.log(str.slice(0, 5));//返回hello

substring() 和slice()的作用一样

var str = "hello world";
console.log(str.substring(0, 5));//返回hello

substr() 截取字符串,参数为开始位置和截取的个数,不改变原字符串

var str = "hello world";
console.log(str.substr(6, 5));//world

trim() 去除前后空格,不改变原字符串

var str = "   hello world      ";
console.log(str.trim());//返回hello world

toLowerCase() 将字符串转为小写,不改变原字符串

var str = "HELLO WORLD";
console.log(str.toLowerCase());//返回hello world

toUpperCase() 将字符串转为大写,不改变原字符串

var str = "hello world";
console.log(str.toUpperCase());//返回HELLO WORLD

match() 可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配

var str="Hello world!"
document.write(str.match("world") + "<br />");//返回world
document.write(str.match("World") + "<br />");//返回null

replace() 用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串

var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School"));//Visit W3School!

search() 用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串

var str="Visit W3School!"
document.write(str.search(/W3School/));//6

split() 用于把一个字符串分割成字符串数组

var str="How are you doing today?"
document.write(str.split(" ") + "<br />");//How,are,you,doing,today?
document.write(str.split("") + "<br />");//H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
document.write(str.split(" ",3));//How,are,you

toString() 把数组转换为字符串,然后以逗号连接输出显示。

var a = [1,2,3,4,5,6,7,8,9,0];  //定义数组
var s = a.toString();  //把数组转换为字符串
console.log(s);  //返回字符串“1,2,3,4,5,6,7,8,9,0”
console.log(typeof s);  //返回字符串string,说明是字符串类型

join() 方法可以把数组转换为字符串,不过它可以指定分隔符。在调用 join() 方法时,可以传递一个参数作为分隔符来连接每个元素。如果省略参数,默认使用逗号作为分隔符,这时与 toString() 方法转换操作效果相同。

var a = [1,2,3,4,5];  //定义数组
var s = a.join("==");  //指定分隔符
console.log(s);  //返回字符串“1==2==3==4==5”

splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目

arr.splice(2,0,"William");//从arr数组索引2添加一个数组
arr.splice(2,1);//删除arr数组索引2
arr.splice(2,1,"William");//删除arr数组索引2并且添加一个
经验js字符串
朗读
赞(0)
版权属于:

至尊技术网

本文链接:

https://www.zzwws.cn/archives/4956/(转载时请注明本文出处及文章链接)

评论 (0)