js实现text
使用JavaScript操作文本
在JavaScript中,处理文本(字符串)是常见的操作。可以通过多种方式创建、修改和操作文本内容。
创建文本字符串
使用单引号、双引号或反引号创建字符串:
const str1 = '单引号字符串';
const str2 = "双引号字符串";
const str3 = `模板字符串`;
字符串拼接
使用加号运算符或模板字符串拼接文本:
const name = "张三";
const greeting = "你好," + name + "!";
const templateGreeting = `你好,${name}!`;
常用字符串方法
获取字符串长度:
const text = "Hello";
const length = text.length; // 5
获取特定位置的字符:

const char = text.charAt(1); // 'e'
字符串切片:
const slice = text.slice(1, 3); // 'el'
查找子字符串:
const index = text.indexOf('l'); // 2
替换文本:

const newText = text.replace('Hello', 'Hi'); // 'Hi'
大小写转换:
const upper = text.toUpperCase(); // 'HELLO'
const lower = text.toLowerCase(); // 'hello'
模板字符串
模板字符串支持多行文本和表达式插值:
const multiLine = `
这是
多行
文本
`;
const calc = `1 + 2 = ${1 + 2}`; // '1 + 2 = 3'
正则表达式处理文本
使用正则表达式进行复杂文本匹配和替换:
const pattern = /\d+/g;
const result = "a1b2c3".match(pattern); // ['1', '2', '3']
HTML文本操作
通过DOM操作修改HTML元素的文本内容:
document.getElementById('myElement').textContent = "新文本";
document.getElementById('myElement').innerHTML = "<strong>加粗文本</strong>";






