簡體   English   中英

用javascript分隔字符串

[英]separate split string with javascript

我有以下4種任務類型的字符串:

ManagerTask
CoordinatorTask
BossTask
EmployTask

我需要一個方法/正則表達式來拆分/分離這些字符串:結果應為:

Manager Task
Coordinator Task
Boss Task
Employ Task

謝謝!

請嘗試以下操作:

 function splitString(str){ return str.substring(0,str.lastIndexOf("T"))+" "+str.substring(str.lastIndexOf("T")); } console.log(splitString("ManagerTask")); 

 var taskStrs = ['ManagerTask', 'CoordinatorTask', 'BossTask', 'EmployTask', "TaskMakerTask"]; function formatTaskName(task) { var lastTaskInd = task.lastIndexOf("Task"); if(lastTaskInd == -1) { return task; } return task.substring(0,lastTaskInd) + " " + task.substring(lastTaskInd); } for(var i = 0; i < taskStrs.length; i++) { console.log(formatTaskName(taskStrs[i])); } 

您可以使用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(/([AZ])/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')); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM