// 示例代码:JavaScript 中的字符串操作
// 定义一个字符串
let greeting = "Hello, world!";
// 获取字符串的长度
console.log(greeting.length); // 输出: 13
// 字符串拼接
let name = "Alice";
let welcomeMessage = "Welcome to the party, " + name + "!";
console.log(welcomeMessage); // 输出: Welcome to the party, Alice!
// 使用模板字符串(Template Literals)
let welcomeMessage2 = `Welcome to the party, ${name}!`;
console.log(welcomeMessage2); // 输出: Welcome to the party, Alice!
// 查找子字符串的位置
let index = greeting.indexOf("world");
console.log(index); // 输出: 7
// 替换子字符串
let newGreeting = greeting.replace("world", "JavaScript");
console.log(newGreeting); // 输出: Hello, JavaScript!
// 转换为大写或小写
console.log(greeting.toUpperCase()); // 输出: HELLO, WORLD!
console.log(greeting.toLowerCase()); // 输出: hello, world!
// 截取字符串
let substring = greeting.slice(0, 5);
console.log(substring); // 输出: Hello
// 检查字符串是否以特定子字符串开头或结尾
console.log(greeting.startsWith("Hello")); // 输出: true
console.log(greeting.endsWith("!")); // 输出: true
// 分割字符串为数组
let words = greeting.split(", ");
console.log(words); // 输出: ["Hello", "world!"]
'
或 "
) 包裹文本。.length
属性。+
运算符或模板字符串(反引号 `
)进行拼接。.indexOf()
方法返回子字符串的位置。.replace()
方法替换指定的子字符串。.toUpperCase()
和 .toLowerCase()
方法。.slice()
方法从指定位置截取字符串。.startsWith()
和 .endsWith()
方法。.split()
方法将字符串分割成数组。上一篇:js string date
下一篇:js 获取文件类型
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站