length
:返回字符串的长度。
const str = "Hello World"; console.log(str.length); // 11
toUpperCase()
:将字符串转换为大写字母。const str = "hello"; console.log(str.toUpperCase()); // "HELLO"
toLowerCase()
:将字符串转换为小写字母。
const str = "WORLD"; console.log(str.toLowerCase()); // "world"
charAt(index)
:返回指定索引位置的字符。
const str = "Hello"; console.log(str.charAt(0)); // "H" console.log(str.charAt(3)); // "l"
substring(startIndex, endIndex)
:返回从 startIndex 到 endIndex(不包括)之间的子字符串。
const str = "Hello World"; console.log(str.substring(0, 5)); // "Hello" console.log(str.substring(6)); // "World"
split(separator)
:将字符串按照指定的分隔符分割成数组。
const str = "apple,banana,orange"; const fruits = str.split(","); console.log(fruits); // ["apple", "banana", "orange"]
replace(oldValue, newValue)
:将字符串中的 oldValue 替换为 newValue。
const str = "Hello World"; const newStr = str.replace("World", "JavaScript"); console.log(newStr); // "Hello JavaScript"
trim()
:去除字符串两端的空格。
const str = "Hello World"; console.log(str.length); // 11
length
:返回字符串的长度。
const str = " Hello "; console.log(str.trim()); // "Hello"
indexOf(searchValue, startIndex)
:返回指定搜索值在字符串中第一次出现的索引位置,如果未找到则返回 -1。
const str = "Hello World"; console.log(str.indexOf("o")); // 4 console.log(str.indexOf("l", 3)); // 3 console.log(str.indexOf("JavaScript")); // -1
concat(...strings)
:将多个字符串连接成一个新的字符串。
const str1 = "Hello"; const str2 = "World"; const str3 = "!"; console.log(str1.concat(str2, str3)); // "HelloWorld!"
startsWith(searchValue, startIndex)
:检查字符串是否以指定的搜索值开头,返回布尔值。
const str = "Hello World"; console.log(str.startsWith("Hello")); // true console.log(str.startsWith("World", 6)); // true console.log(str.startsWith("JavaScript")); // false
endsWith(searchValue, endIndex)
:检查字符串是否以指定的搜索值结尾,返回布尔值
const str = "Hello World"; console.log(str.endsWith("World")); // true console.log(str.endsWith("Hello", 5)); // true console.log(str.endsWith("JavaScript")); // false
这些只是一些常见的字符串处理方法,JavaScript还提供了更多的字符串处理方法,根据具体的需求,可以选择合适的方法进行字符串的处理和操作。