JavaScript trim() 和 replace() 方法详解:去除空格和替换字符串
trim() 方法用于去除字符串两端的空格或制表符等空白字符,返回去除空白字符后的新字符串。例如:
const str = ' hello world ';
const trimmedStr = str.trim(); // 'hello world'
replace() 方法用于将字符串中的指定子字符串或正则表达式匹配的字符串替换为新的字符串,并返回替换后的新字符串。例如:
const str = 'hello world';
const replacedStr = str.replace('world', 'everyone'); // 'hello everyone'
replace() 方法也支持使用正则表达式进行匹配和替换。例如:
const str = 'hello world';
const replacedStr = str.replace(/o/g, 'e'); // 'helle werld'
其中,'/o/g' 是一个正则表达式,表示匹配字符串中所有的小写字母 'o'。在替换时,将所有匹配到的 'o' 替换为 'e'。
原文地址: https://www.cveoy.top/t/topic/nJcF 著作权归作者所有。请勿转载和采集!