js 字符串操作函数有哪些

2020-08-13  本文已影响0人  前端阿峰

对字符串的操作做以下整理

1、字符串转换——toString

var num=24;
var mystr=num.toString();    //"24"
var num=24;
var mystr="" + num;    //"24"

2、字符串分割——split

var mystr="this is a test";
var arr1=mystr.split("");  //["t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "s", "t"]

3、字符串替换

var mystr="this is a test";
var replaceStr=mystr.replace("this"," ");  //   is a test

4、获取字符串长度——length

var mystr="this is a test";
var strLen=mystr.length; // 14

5、查询子字符串——indexOf

var mystr="Hello world!";
var index=mystr.indexOf("llo");    //2
var index1=mystr.indexOf("l");    //2
var index2=mystr.indexOf("l",3);    //3

6、返回指定位置的字符或其字符编码值——charAt

var mystr="Hello World!";
var index=mystr.charAt(7);    //o

7、 字符串匹配——match

var mystr="this is a test";
var strMatch=mystr.match('is'); // ["is", index: 2, input: "this is a test", groups: undefined]

8、字符串连接

var mystr1="Hello";
var mystr2="world!";
var newStr=mystr1+" "+mystr2;    //Hello world!

9、字符串切割和提取——slice、substring、substr

第一种,slice()函数:

var mystr="hello world!";
var sliceStr1=mystr.slice(-3);    //ld!
var sliceStr2=mystr.slice(-3,-1);    //ld
var sliceStr3=mystr.slice(3);    //lo world!
var sliceStr4=mystr.slice(3,7);    //lo w

第二种:substring()函数:

var mystr="hello world!";
var sliceStr1=mystr.substring(3);    //lo world!
var sliceStr2=mystr.substring(3,7);    //lo w

第三种:substr()函数:

var mystr="hello world!";
var sliceStr1=mystr.substr(3);    //lo world!
var sliceStr2=mystr.substr(3,7);    //lo wo

10、字符串大小写转换——toLowerCase、toUpperCase

var mystr="Hello World!";
var lowCaseStr=mystr.toLowerCase();    //hello world!
var upCaseStr=mystr. toUpperCase();    //HELLO WORLD!

11、字符串去空格——trim

var mystr="     hello world      ";  
var trimStr=mystr.trim();    //hello world
上一篇 下一篇

猜你喜欢

热点阅读