我有一个字符串数组,如下所示:
const strings = ['Prepayment', 'Postpayment', 'Complete']
const addDash = (str: string) =>
str.startsWith('Pre') || str.startsWith('Post') ? str.replace(' ', '-') : str;
Run Code Online (Sandbox Code Playgroud)
我想要以下数组:
const result = strings.map(str => addDash(str))
// => ['Pre-payment', 'Post-payment', 'Complete'] // want result to equal this
Run Code Online (Sandbox Code Playgroud)
谁能建议什么正则表达式可以帮助我完成这项任务?
您可以使用
const addDash = (str) => str.replace(/^P(?:re|ost)\B/, '$&-');
const strings = ['Prepayment', 'Postpayment', 'Complete']
const result = strings.map(str => addDash(str));
console.log(result);Run Code Online (Sandbox Code Playgroud)
该^P(?:re|ost)\B模式匹配
^ - 字符串的开始P(?:re|ost)- Pre或Post\B - 后跟一个字符字符。$& 是对与正则表达式匹配的整个值的反向引用。
请参阅正则表达式演示。