tft每日頭條

 > 科技

 > 前端人需要了解的12個常用字符串操作

前端人需要了解的12個常用字符串操作

科技 更新时间:2024-07-22 08:16:48
目錄

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

,

更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!

查看全部

相关科技资讯推荐

热门科技资讯推荐

网友关注

Copyright 2023-2024 - www.tftnews.com All Rights Reserved