一、字符串的定義和讀取
JS中字符串可以用單引號或雙引號表示,兩者沒有區別。例如:
let str1 = 'hello world'; let str2 = "hello world";
字符串也可以用String對象來表示:
let str3 = new String("hello world");
JS可以通過下標和循環遍歷字符串中的每個字符:
let str = "hello world"; for(let i=0; i<str.length; i++){ console.log(str[i]); }
以上代碼會從頭到尾輸出字符串中的每個字符,即:
h e l l o w o r l d
二、字符串的操作和轉換
JS中有很多方法可以對字符串進行操作和轉換。例如,可以用charAt()方法獲取字符串中某個位置的字符:
let str = "hello world"; console.log(str.charAt(0)); //輸出h
JS還可以用substring()方法獲取字符串中的子字符串:
let str = "hello world"; console.log(str.substring(0, 5)); //輸出hello
JS還可以用toUpperCase()方法將字符串中的所有字符轉換成大寫:
let str = "hello world"; console.log(str.toUpperCase()); //輸出HELLO WORLD
三、字符串的匹配和替換
JS中可以使用正則表達式對字符串進行匹配。例如,下面的代碼使用正則表達式來檢查字符串中是否包含hello:
let str = "hello world"; if(str.match(/hello/)){ console.log("包含hello"); }else{ console.log("不包含hello"); }
JS也可以使用replace()方法來替換字符串中的子字符串。例如,下面的代碼可以將字符串中的world替換成javascript:
let str = "hello world"; console.log(str.replace("world", "javascript")); //輸出hello javascript
四、字符串的拼接和分割
JS中可以使用加號來拼接字符串。例如:
let str1 = "hello"; let str2 = "world"; console.log(str1 + " " + str2); //輸出hello world
JS中還可以使用split()方法來將字符串分割成數組。例如,下面的代碼將字符串按照空格分割成了數組:
let str = "hello world"; let arr = str.split(" "); console.log(arr); //輸出["hello", "world"]
五、字符串的編碼和解碼
JS中可以使用encodeURI()和decodeURI()方法對URL進行編碼和解碼。例如,下面的代碼將https://www.google.com/編碼成了https%3A%2F%2Fwww.google.com%2F:
let url = "https://www.google.com/"; let encodedUrl = encodeURI(url); console.log(encodedUrl); //輸出https%3A%2F%2Fwww.google.com%2F
JS中也可以使用escape()和unescape()方法對字符串進行編碼和解碼。例如,下面的代碼將hello world編碼成了hello%20world:
let str = "hello world"; let encodedStr = escape(str); console.log(encodedStr); //輸出hello%20world
結語
JS能夠對字符串進行的操作是非常多的,上面只是列舉了幾個常見的操作。通過細心研究,可以發現JS中還有很多有用的方法可以用來處理字符串。相信在今後的工作和學習中,我們將會遇到更多對字符串的操作,也希望上述內容能夠對讀者有所幫助。
原創文章,作者:RCHCL,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/367960.html