js实现text
使用JavaScript实现文本操作
JavaScript提供了多种方式来处理和操作文本。以下是一些常见的文本操作方法:
字符串拼接
const str1 = 'Hello';
const str2 = 'World';
const result = str1 + ' ' + str2;
console.log(result); // 输出: Hello World
模板字符串
const name = 'Alice';
const age = 25;
const message = `My name is ${name} and I'm ${age} years old.`;
console.log(message);
字符串方法
const text = 'JavaScript is awesome';
// 获取长度
const length = text.length;
// 查找子字符串
const index = text.indexOf('awesome');
// 提取子字符串
const subStr = text.substring(0, 10);
// 替换文本
const newText = text.replace('awesome', 'amazing');
HTML文本操作

// 获取元素文本
const element = document.getElementById('myElement');
const elementText = element.textContent;
// 设置元素文本
element.textContent = 'New text content';
// 创建文本节点
const textNode = document.createTextNode('Dynamic text');
document.body.appendChild(textNode);
文本格式化处理
日期格式化
const date = new Date();
const formattedDate = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
数字格式化
const number = 1234.567;
const formattedNumber = number.toFixed(2); // "1234.57"
const localizedNumber = number.toLocaleString(); // 根据地区格式化
正则表达式处理文本
const text = 'Contact us at support@example.com or sales@example.org';
// 提取所有电子邮件
const emails = text.match(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g);
// 验证电子邮件格式
const isValidEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test('test@example.com');
文本编码与解码
Base64编码解码

const text = 'Hello World';
const encoded = btoa(text); // 编码
const decoded = atob(encoded); // 解码
URL编码解码
const url = 'https://example.com?q=JavaScript 教程';
const encodedURL = encodeURIComponent(url);
const decodedURL = decodeURIComponent(encodedURL);
文本分析与处理
统计词频
function countWords(text) {
const words = text.toLowerCase().split(/\s+/);
const frequency = {};
words.forEach(word => {
frequency[word] = (frequency[word] || 0) + 1;
});
return frequency;
}
文本截断
function truncate(text, maxLength) {
return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
}
这些方法涵盖了JavaScript中处理文本的常见需求,可以根据具体场景选择合适的方法或组合使用多个方法。






