ReactJS中如何去除字符串中的引号?含split后处理场景
去除字符串中的引号(JavaScript实现)
你已经用str.split('.')拆分了段落,现在要去掉拆分后字符串里的引号(包括示例里的中文引号“”),可以用正则表达式结合replace()方法实现,给你两种方案:
方案一:先处理引号再拆分(更高效)
先把整个字符串里的引号全部去掉,再执行拆分操作:
const str = `My mamma stood up and lifted a box off the ground. “We’re in America, Rune. They speak English here. You’ve been speaking English for as long as you’ve been speaking Norwegian. It’s time to use it.”`; // 全局替换所有中文引号(“”)和英文双引号("") const processedStr = str.replace(/[“”"]/g, ''); // 拆分处理后的字符串 const splitResult = processedStr.split('.');
方案二:拆分后逐个处理元素
如果已经完成了拆分操作,遍历数组里的每个元素,单独去除引号:
const str = `My mamma stood up and lifted a box off the ground. “We’re in America, Rune. They speak English here. You’ve been speaking English for as long as you’ve been speaking Norwegian. It’s time to use it.”`; // 先拆分字符串 const splitArr = str.split('.'); // 遍历数组,逐个去除引号 const cleanedArr = splitArr.map(item => item.replace(/[“”"]/g, ''));
说明
正则表达式/[“”"]/g中的[“”"]是字符集,包含了中文左引号、中文右引号和英文双引号,g标记表示全局替换(即替换所有匹配到的引号)。如果只需要处理中文引号,把正则改成/[“”]/g即可。
处理后你会得到期望的结果:
My mamma stood up and lifted a box off the ground. We’re in America,
Rune. They speak English here. You’ve been speaking English for as long as
you’ve been speaking Norwegian. It’s time to use it.
内容的提问来源于stack exchange,提问作者Trunks
相关产品推荐
相关产品推荐

