目录

01. 字符串转数字

02. 获取字符串的某个字符

03. 模板字符串代替拼接

04. 判断字符串中的特定序列

05. 字符串分割成数组 split

06. 字符串替换 splice

07. 获取字符串首次和最后出现的位置

08. 字符串去除首尾空格

09. 获取介于两个下标之间的字符串

10. 字符串大小写

11. 字符串的反转、复制和填充

12. 替换文本中所有的字符串

正文

01.字符串转数字

let str = "32.14"; let num = str console.log(num)

02.获取字符串的某个字符

// 以前的方法 let str = "hello world!" let str1 = str.charAt(2) //简写 let str2 = str[2] console.log(str1) console.log(str2)

03. 模板字符串代替拼接

let name = 'gwz' // 拼接 console.log('name is:' name '!') // 模板字符串 console.log(`name is:${name}!`)

04. 判断字符串中的特定序列

const name1 = 'zhangsan'; const name2 = 'lisi' const text ='Helllo,My name is zhangsan' // 是否包含 console.log(text.includes(name1)) // true console.log(text.includes(name2)) // false // 是否开头 console.log(text.startsWith(name1)) // false // 是否结尾 console.log(text.endsWith(name1)) // true

05. 字符串分割成数组 split

const str = "hell,world!"; const arr = str.split(","); console.log(arr) //["hell", "world!"]

06. 字符串替换 splice

const str = "hell,wold!"; const newStr = str.replace(/wold/,"world") console.log(newStr)

07. 获取字符串首次和最后出现的位置

const str = "hello,wold!"; // 首次位置 console.log(str.indexOf("o")) //4 // 最后出现的位置 console.log(str.lastIndexOf("o")) //7

08. 字符串去除首尾空格

const str = " hello "; const newStr = str.trim() console.log(newStr)

09. 获取介于两个下标之间的字符串

var str = "hello world"; console.log(str.slice(4)); //o world console.log(str.slice(2,7)); //llo w

10. 字符串大小写

let str = "Hello World!" // 全部小写 console.log(str.toLowerCase()) console.log(str.toLocaleLowerCase()) // 全部大写 console.log(str.toUpperCase()) console.log(str.toLocaleUpperCase())

11. 字符串的反转、复制和填充

let name = "zhangsan" let num = '001' //反转 const reverseName = [...name].reverse().join('') console.log(reverseName) //复制3遍 console.log(name.repeat(3)) //首位填充&,长度为6 console.log(num.padStart(6,'&')) //末尾填充*,长度为6 console.log(num.padEnd(6,'*'))

12. 替换文本中所有的字符串

const text = "hello,wold!hello,wold!"; //方法一:replace console.log(text.replace(/wold/g,"world")) //方法二:正则加repalce方法并每个添加索引 var reg = new RegExp("wold", "gi"); //创建正则RegExp对象 var i = 0 var newstr = text.replace(reg, function () { i ; return `world${i}`; }); console.log(newstr)

写在最后

如果喜欢,可以点下关注与大家一起探讨一起分享,最后希望与每一个努力的人同行,一起进步,一起加油,谢谢大家!

前端人需要了解的12个常用字符串操作(前端人需要了解的12个常用字符串操作)(1)

,