字串的17種方法,,,,,,
length
:回傳字串的長度,
const str = "Hello, World!";
console.log(str.length); // 輸出 13
charAt(index)
:回傳指定索引位置的字符,
const str = "Hello, World!";
console.log(str.charAt(4)); // 輸出 o
concat(str1, str2, ...)
:連接兩個或多個字串,并回傳新的字串,
const str1 = "Hello";
const str2 = "World";
const str3 = str1.concat(", ", str2);
console.log(str3); // 輸出 Hello, World
indexOf(substring, start)
:回傳子字串在原字串中第一次出現的位置,如果未找到則回傳-1,
const str = "Hello, World!";
console.log(str.indexOf("World")); // 輸出 7
console.log(str.indexOf("foo")); // 輸出 -1
console.log(str.indexOf("foo") === -1); // true
lastIndexOf(substring, start)
:回傳子字串在原字串中最后一次出現的位置,如果未找到則回傳-1,
const str = "Hello, World!";
console.log(str.lastIndexOf("o")); // 輸出 8
console.log(str.lastIndexOf("foo")); // 輸出 -1
slice(start, end)
:從原字串中提取指定范圍的字符,并回傳新的字串,
const str = "Hello, World!";
console.log(str.slice(7, 12)); // 輸出 World
substring(start, end)
:從原字串中提取指定范圍的字符,并回傳新的字串,與 slice()
類似,但不支持負數引數,
const str = "Hello, World!";
console.log(str.substring(7, 12)); // 輸出 World
console.log(str.substring(2)); // 輸出 llo, World!
substr(start, length)
:從原字串中提取指定長度的字符,并回傳新的字串,
const str = "Hello, World!";
console.log(str.substr(7, 5)); // 輸出 World
console.log(str.substr(2, 3)); // 輸出 llo
toLowerCase()
:將字串轉換為小寫,
const str = "Hello, World!";
console.log(str.toLowerCase()); // 輸出 hello, world!
toUpperCase()
:將字串轉換為大寫,
const str = "Hello, World!";
console.log(str.toUpperCase()); // 輸出 HELLO, WORLD!
trim()
:去除字串兩端的空格, 中間的空格不行,
const str = " Hello, World! ";
console.log(str.trim()); // 輸出 Hello, World!
split(separator)
:將字串按照指定的分隔符分割為陣列,
const str = "Hello, World!";
const arr = str.split(", ");
console.log(arr); // 輸出 ["Hello", "World!"]
replace(searchValue, replaceValue)
:將字串中的指定內容替換為新的內容,
const str = "Hello, World!";
const newStr = str.replace("World", "Universe");
console.log(newStr); // 輸出 Hello, Universe!
startsWith(searchString, position)
:判斷字串是否以指定的子字串開頭,
const str = "Hello, World!";
console.log(str.startsWith("Hello")); // 輸出 true
console.log(str.startsWith("World")); // 輸出 false
endsWith(searchString, position)
:判斷字串是否以指定的子字串結尾,
const str = "Hello, World!";
console.log(str.endsWith("World!")); // 輸出 true
console.log(str.endsWith("Hello")); // 輸出 false
includes(searchString, position)
:判斷字串是否包含指定的子字串,
const str = "Hello, World!";
console.log(str.includes("World")); // 輸出 true
console.log(str.includes("foo")); // 輸出 false
match(regexp)
:通過正則運算式在字串中搜索匹配項,并回傳匹配結果的陣列,
const str = "Hello, World!";
const matches = str.match(/[a-zA-Z]+/g);
console.log(matches); // 輸出 ["Hello", "World"]
const str1 = "Hello,12131,a23,232,232 World!";
const matches1 = str1.match(/[a-zA-Z]+/g);
console.log(matches1); // 輸出 ['Hello', 'a', 'World']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/557054.html
標籤:JavaScript
上一篇:前端Vue仿美團地址管理組件串列組件 可用于電商平臺識訓地址管理
下一篇:返回列表