一、字元串的定義和讀取
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-tw/n/367960.html