2024年05月10日 建站教程
在JavaScript中,如果你想要将字符串中的所有英文标点符号替换为对应的中文标点符号,或者去掉所有标点符号,我们可以利用replace来实现这个功能,下面web建站小编给大家简单介绍一下具体实现代码!
let str = "Hello, world! Nice to me you? I'm fine. Thanks!";
// 自定义中英文标点符号的对应关系
let punctuationMap = {
',': ',',
'.': '。',
'!': '!',
'?': '?',
';': ';',
':': ':',
'(': '(',
')': ')',
'[': '[',
']': ']',
'{': '{',
'}': '{',
'"': '“',
"'": '‘'
};
// 利用正则表达式和回调函数进行替换
let newStr = str.replace(/[.,!?;:"'()\[\]{}]/g, function(match) {
return punctuationMap[match] || match;
});
console.log('输出结果:', newStr);
//输出结果: Hello, world! Nice to me you? I‘m fine。 Thanks!
let str = "Hello, world! Nice to me you? I'm fine. Thanks!";
let newStr = str.replace(/[.,!?;:'"()\[\]{}]/g, '');
console.log('输出结果:', newStr);
输出结果: Hello world Nice to me you Im fine Thanks
本文链接:http://so.lmcjl.com/news/4197/