我有以下4个任务类型的字符串:

我需要一个方法/正则表达式来拆分/分离这些字符串:结果应为:

ManagerTask
CoordinatorTask
BossTask
EmployTask

谢谢!

最佳答案

您可以使用Regex匹配task和'Task'之前的所有内容,并在匹配的组之间添加空格:



const modify = text => text.replace(/(.+)(Task)/, '$1 $2');

console.log(modify('ManagerTask'));
console.log(modify('CoordinatorTask'));
console.log(modify('BossTask'));
console.log(modify('EmployTask'));





另外,如果您需要针对此问题的常规解决方案,则可以使用:



const modify = text => text
  // Find all capital letters and add space before them
  .replace(/([A-Z])/g, ' $1')
  // Remove the first space - otherwise result would be for example ' OfficeManagerTask'
  .substring(1);

console.log(modify('OfficeManagerTask'));
console.log(modify('AngryBossTask'));

console.log(modify('ManagerTask'));
console.log(modify('CoordinatorTask'));
console.log(modify('BossTask'));
console.log(modify('EmployTask'));

关于javascript - 用javascript分隔字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50765328/

10-11 20:52