Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js string

作者:末世修罗   发布日期:2025-10-03   浏览:81

// 示例代码: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 获取文件类型

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站