微信小程序 ↵符号替换
...大约 1 分钟
微信小程序 ↵符号替换
微信小程序,将下面文字以↵
符号,进行分割,并统计分割后每个数组元素的文字个数
const string = 'n. 墓穴,坟墓;死亡↵adj. 重大的;严肃的;黯淡的↵vt. 雕刻;铭记'
很可惜,微信小程序、H5 无法直接获取↵
符号,也即
string.split('↵')
// ["n. 墓穴,坟墓;死亡↵adj. 重大的;严肃的;黯淡的↵vt. 雕刻;铭记"]
因此,我们需要先把↵
符号进行编码
- 使用
encodeURIComponent
对内容进行编码,得知↵
编码为%E2%86%B5
const encode = encodeURIComponent('↵')
console.log(encode)
// %E2%86%B5
把需要替换的所有文字使用
encodeURIComponent
进行编码,然后把%E2%86%B5
替换掉你需要的内容把替换掉的内容使用
decodeURIComponent
解码重新解码回来
整体操作函数,比如我需要将↵
替换为,
const replaceNewlineSymbol = (text) => {
const encodeText = encodeURIComponent(text) // encodeURIComponent 对传入字段进行编码
const regexp = RegExp('%E2%86%B5', 'g') // RegExp 对象用于将文本与一个模式匹配,g 为全局匹配的意思
const newText = encodeText.replace(regexp, ',') // replace 替换,意思是根据正则规则将 '%E2%86%B5' 全局替换为 ‘,’
return decodeURIComponent(newText) // decodeURIComponent 对替换后的字段进行解码
}
const string = 'n. 墓穴,坟墓;死亡↵adj. 重大的;严肃的;黯淡的↵vt. 雕刻;铭记'
replaceNewlineSymbol(string)
// 'n. 墓穴,坟墓;死亡,adj. 重大的;严肃的;黯淡的,vt. 雕刻;铭记'
总结
- js 无法直接解析
↵
符号,所以无法直接将↵
符号进行替换- 通过
encodeURIComponent
将文本编码,并将↵
的编码%E2%86%B5
进行替换,替换后再通过decodeURIComponent
解码回来
Powered by Waline v2.15.5