I have this 4 task type of string:
ManagerTask
CoordinatorTask
BossTask
EmployTask
I need a method/regexp to split/separate these strings: The result should be:
Manager Task
Coordinator Task
Boss Task
Employ Task
Thank you!
asked Jun 8, 2018 at 16:58
tomatito
4111 gold badge6 silver badges17 bronze badges
3 Answers 3
Try the following:
function splitString(str){
return str.substring(0,str.lastIndexOf("T"))+" "+str.substring(str.lastIndexOf("T"));
}
console.log(splitString("ManagerTask"));
answered Jun 8, 2018 at 17:00
amrender singh
8,2594 gold badges27 silver badges30 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
tomatito
you response is fine but i can not use concatenation with eslint. Please can you change the code with template `` instead of concatenation? thank you
You can use Regex to match anything before task and the 'Task' and add space between these to matched groups:
const modify = text => text.replace(/(.+)(Task)/, '1ドル 2ドル');
console.log(modify('ManagerTask'));
console.log(modify('CoordinatorTask'));
console.log(modify('BossTask'));
console.log(modify('EmployTask'));
Also if you needed general solution for this issue you can use:
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'));
answered Jun 8, 2018 at 17:10
user3210641
1,6311 gold badge11 silver badges14 bronze badges
2 Comments
tomatito
The best and shortest response. Thank you!
user3210641
Consider using the updated answer for possible future cases.
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]));
}
answered Jun 8, 2018 at 17:04
Tom G
3,6701 gold badge23 silver badges19 bronze badges
1 Comment
Tom G
@tomatilo, The jQuery has been removed, it was only to show the result of the Javascript function
lang-js