在 JavaScript 中,可以使用 substring()
和 substr()
方法來截取字符串。
substring(startIndex [, endIndex])
方法用于從字符串中提取子字符串。
-
startIndex
參數(shù)是必需的,表示要截取的子字符串的起始位置。 -
endIndex
參數(shù)是可選的,表示要截取的子字符串的結(jié)束位置。如果省略,則將截取到字符串尾部。
substring()
方法返回一個新的字符串,不會修改原始字符串。
例如,假設(shè)有一個字符串 "Hello, world!"
,要從第 7 個字符開始截取,可以使用以下代碼:
const str = "Hello, world!";
const subStr = str.substring(7);
console.log(subStr); // 輸出 "world!"
如果要從第 1 個字符開始截取到第 5 個字符,則可以使用以下代碼:
const str = "Hello, world!";
const subStr = str.substring(0, 5);
console.log(subStr); // 輸出 "Hello"
substr(startIndex [, length])
方法用于從字符串中提取子字符串。
-
startIndex
參數(shù)是必需的,表示要截取的子字符串的起始位置。 -
length
參數(shù)是可選的,表示要截取的子字符串的長度。如果省略,則將截取到字符串尾部。
substr()
方法返回一個新的字符串,不會修改原始字符串。文章來源:http://www.zghlxwxcb.cn/news/detail-431238.html
- 例如,假設(shè)有一個字符串
"Hello, world!"
,要從第 7 個字符開始截取,可以使用以下代碼:
const str = "Hello, world!";
const subStr = str.substr(7);
console.log(subStr); // 輸出 "world!"
如果要從第 1 個字符開始截取 5 個字符,則可以使用以下代碼:文章來源地址http://www.zghlxwxcb.cn/news/detail-431238.html
const str = "Hello, world!";
const subStr = str.substr(0, 5);
console.log(subStr); // 輸出 "Hello"
到了這里,關(guān)于js截取字符串 記錄日常開發(fā)中的小搜索的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!