// 示例代码:JavaScript 字符串操作
// 1. 获取字符串长度
let str = "Hello, world!";
let length = str.length; // length 属性返回字符串的长度
console.log(length); // 输出: 13
// 2. 字符串拼接
let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // 使用 + 操作符拼接字符串
console.log(fullName); // 输出: John Doe
// 3. 字符串转大写或小写
let lowerCaseStr = "hello";
let upperCaseStr = lowerCaseStr.toUpperCase(); // toUpperCase() 方法将字符串转换为大写
console.log(upperCaseStr); // 输出: HELLO
let mixedCaseStr = "HeLlO";
let lowerCaseMixed = mixedCaseStr.toLowerCase(); // toLowerCase() 方法将字符串转换为小写
console.log(lowerCaseMixed); // 输出: hello
// 4. 查找子字符串的位置
let sentence = "The quick brown fox jumps over the lazy dog.";
let index = sentence.indexOf("fox"); // indexOf() 方法返回指定子字符串首次出现的位置
console.log(index); // 输出: 16
// 5. 替换子字符串
let text = "Hello, world!";
let newText = text.replace("world", "JavaScript"); // replace() 方法替换指定子字符串
console.log(newText); // 输出: Hello, JavaScript!
// 6. 提取子字符串
let extractStr = "Hello, world!";
let subStr = extractStr.substring(0, 5); // substring() 方法提取从开始到结束位置之间的子字符串(不包括结束位置)
console.log(subStr); // 输出: Hello
// 7. 分割字符串为数组
let fruits = "apple,banana,orange";
let fruitArray = fruits.split(","); // split() 方法根据指定分隔符将字符串分割成数组
console.log(fruitArray); // 输出: ["apple", "banana", "orange"]
// 8. 检查字符串是否以指定子字符串开头或结尾
let greeting = "Hello, world!";
let startsWithHello = greeting.startsWith("Hello"); // startsWith() 方法检查字符串是否以指定子字符串开头
console.log(startsWithHello); // 输出: true
let endsWithExclamation = greeting.endsWith("!"); // endsWith() 方法检查字符串是否以指定子字符串结尾
console.log(endsWithExclamation); // 输出: true
// 9. 去除字符串两端的空白字符
let whitespaceStr = " Trim this string ";
let trimmedStr = whitespaceStr.trim(); // trim() 方法去除字符串两端的空白字符
console.log(trimmedStr); // 输出: Trim this string
上一篇:js 字符串连接
下一篇:js tostring方法的作用
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站