字符串常用方法

请点开

charAt()

charAt(num)方法可返回指定位置的字符。

num为数值,如果num不在0和字符串长度之间,则其结果返回一个空的字符串

代码如下:

1
2
3
var str="hello world!";
console.log(str.charAt(0)); //h
console.log(str.charAt(1)); //e

charCodeAt()

charCodeAt(num)方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。

num为数值

代码如下:

1
2
3
var str="hello world!";
console.log(str.charCodeAt(0)); //104
console.log(str.charCodeAt(1)); //101

concat()

concat()方法用于连接两个或者多了字符串

多个的顺序为从左向右连接

代码如下:

1
2
3
4
5
6
var str="hello world!";
var str1="我是str1";
var str2="我是str2";
console.log(str.concat(str1)); //hello world!我是str1
console.log(str.concat(str2,str1)); //hello world!我是str2我是str1
console.log(str.concat(str2,"我是字符串",str1)); //hello world!我是str2我是字符串我是str1

fromCharCode()

fromCharCode() 可接受一个指定的 Unicode 值,然后返回一个字符串。

该方法是 String 的静态方法,字符串中的每个字符都由单独的数字 Unicode 编码指定。

代码如下:

1
console.log(String.fromCharCode(65,66,67));	//ABC

indexOf()

indexOf(x1,x2)该方法用来查找字符串中是否x1这个字符串;

x1为想要查找的字符串,x2为想要开始的位置,范围是0-字符串长度-1,如果省略,则,从0开始向右,一般都是省略,如果未找到则返回-1,如果有多个则只返回第一个的位置;

代码如下:

1
2
3
4
var str="hello world!";
console.log(str.indexOf(“h”)); //0
console.log(str.indexOf(“o wor”)); //4
console.log(str.indexOf(“maii”)); //-1

lastIndexOf()

该方法同indexOf(),只不过是从后面向前面查找的

match()

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

该方法类似 indexOf() 和 lastIndexOf(),但是它返回是一个数组里面为匹配到的字符串,而不是字符串的位置。

代码如下:

1
2
var str="h1e2l3l4o wo57r3ld!";
console.log(str.match(/\d/g)) //["1", "2", "3", "4", "5", "7", "3"]

replace()

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

代码如下:

1
2
var str="hello world!";
console.log(str.replace("hello","maii")); //maii world!

search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串。
与indexOf()类似,但是其长用在正则匹配里
代码如下:

1
2
3
var str="hello world!";
console.log(str.search("hello")); //0
console.log(str.search("llo")); //2

slice()

slice(x,y) 方法可从已有的字符串或数组中返回选定的元素。
截取字符串,从x开始到y结束,不含y

代码如下:

1
2
var str="hello world!";
console.log(str.slice(2,5)); //llo

split()

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


1
2
3
4
var str="How are you doing today?";
console.log(str.split(" ")); //How,are,you,doing,today?
console.log(str.split("")); //H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
console.log(str.split(" ",3)); //How,are,you

substr()

substr(x,y) 方法可在字符串中抽取从x下标开始的指定数目的字符。

y为长度,如果y不指定,则一直截取到最后

1
2
3
var str="hello world!";
console.log(str.substr(2,5)); //oll w
console.log(str.substr(2)); //llo world!

substring()

substring() 方法用于提取字符串中介于两个指定下标之间的字符。

和上一个方法相同,不做演示

toLowerCase()

toLowerCase() 方法用于把字符串转换为小写。

代码如下:

1
2
var str="HELLO WORLD!";
console.log(str.toLowerCase()); //hello world!

toUpperCase()

toUpperCase():全部字符变为大写,返回新字符串。

代码如下:

1
2
var str="hello world!";
console.log(str.toLowerCase()); //HELLO WORLD!

valueOf()

valueOf() 方法可返回 Boolean 对象的原始值。

1
2
var bol=true;
console.log(bol.valueOf()); //true肯定是true了貌似没什么用,如果不是布尔类型,直接输出该值