我有一个像这样的字符串:
- - This is the place where the people like to join think-tanks and have fun.
我显然可以使用以下任一方法将所有连字符替换为空格:
my_string.replace(/-/g, ' ')
my_string.split('-').join(' ')
我只需要用空格替换智囊团中的连字符。其他连字符可以保留。
如何仅定位字符串内字母之间的连字符?
最佳答案
只需使用 \w
捕获字母,然后用空格替换破折号”
str.replace(/(\w)\-(\w)/gi, '$1 $2')
元字符一词是[0-9a-zA-Z_]
的简写,即包括数字、大小写字母和下划线。
const str = '- - This is the place where the people like to join think-tanks and have fun.';
console.log(str.replace(/(\w)\-(\w)/gi, '$1 $2'));
关于javascript - 仅在特定字符之间出现时替换文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59630864/