在 QML 中,QML 提供了许多字符串操作函数,包括字符串的操作、查找、分割、拼接等。下面列出了一些常用的字符串操作函数,并附带简单的解释和示例。
1. String.length
获取字符串的长度。
var text = "Hello, World!"
console.log(text.length) // 输出: 13
2. String.indexOf(substring)
查找子字符串第一次出现的位置。如果未找到,返回 -1
。
var text = "Hello, World!"
console.log(text.indexOf("World")) // 输出: 7
console.log(text.indexOf("QML")) // 输出: -1
3. String.lastIndexOf(substring)
查找子字符串最后一次出现的位置。如果未找到,返回 -1
。
var text = "Hello, World! World!"
console.log(text.lastIndexOf("World")) // 输出: 14
4. String.charAt(index)
获取字符串中特定索引的字符。
var text = "Hello, World!"
console.log(text.charAt(0)) // 输出: H
console.log(text.charAt(7)) // 输出: W
5. String.toUpperCase()
将字符串中的字母转换成大写。
var text = "Hello, World!"
console.log(text.toUpperCase()) // 输出: HELLO, WORLD!
6. String.toLowerCase()
将字符串中的字母转换成小写。
var text = "Hello, WORLD!"
console.log(text.toLowerCase()) // 输出: hello, world!
7. String.trim()
去除字符串开头和结尾的空格。
var text = " Hello, World! "
console.log(text.trim()) // 输出: "Hello, World!"
8. String.startsWith(substring)
检查字符串是否以指定的子字符串开头。
var text = "Hello, World!"
console.log(text.startsWith("Hello")) // 输出: true
console.log(text.startsWith("World")) // 输出: false
9. String.endsWith(substring)
检查字符串是否以指定的子字符串结尾。
var text = "Hello, World!"
console.log(text.endsWith("World!")) // 输出: true
console.log(text.endsWith("Hello")) // 输出: false
10. String.slice(startIndex, endIndex)
提取字符串的一部分,从 startIndex
开始,到 endIndex
(不包括 endIndex
)。
var text = "Hello, World!"
console.log(text.slice(7, 12)) // 输出: "World"
11. String.substring(startIndex, endIndex)
与 slice
类似,但不接受负数索引。
var text = "Hello, World!"
console.log(text.substring(7, 12)) // 输出: "World"
12. String.replace(searchValue, replaceValue)
替换字符串中第一个匹配的子字符串。
var text = "Hello, World!"
console.log(text.replace("World", "QML")) // 输出: "Hello, QML!"
13. String.split(delimiter)
将字符串按指定的分隔符拆分成数组。
var text = "a,b,c,d"
var result = text.split(",")
console.log(result) // 输出: ["a", "b", "c", "d"]
14. String.concat(stringToAppend)
拼接字符串,返回一个新字符串。
var text = "Hello"
var newText = text.concat(", World!")
console.log(newText) // 输出: "Hello, World!"
15. String.repeat(count)
返回一个新字符串,该字符串将原始字符串重复指定次数。
var text = "Hello"
console.log(text.repeat(3)) // 输出: HelloHelloHello
16. String.includes(substring)
检查字符串是否包含指定子字符串。
var text = "Hello, World!"
console.log(text.includes("World")) // 输出: true
console.log(text.includes("QML")) // 输出: false