1 回答
TA贡献1876条经验 获得超7个赞
该解决方案依赖于按单词拆分和计算transfer. 它还会检测最后一个单词之前是否有整数,如果是,则按以下代码所述处理这种情况:
var name = "Model Transfer 2 transfer";
const name1 = 'Model transfer model transfer';
const name2 = 'Model transfer transfer transfer';
const name3 = 'Model Transfer transfer Transfer';
const name4 = 'Model transfer transfer transfer';
const renameNameOccurrence = (name, occurrenceName) => {
// split by words as lowercased
let s = name.toLowerCase().split(" ")
// Now count the 'transfer' words
let t = 0;
for (var i = 0; i < s.length; i++) {
if (s[i] == "transfer") {
t++;
}
}
// Now see if a integer precedes last word
w = s.length - 2; // -2 since length is base 1, and we need word before last
if (w > 1) { // excluding the assumed 1st word Model
if ( parseInt( s[w] ).toString() == s[w]) {
t++; // increment transfer words, since count is consistent
console.log("hello")
}
}
// Now recompose the string
if (t > 1) {
return name.split(" ")[0] + " Transfer " + t
}
else if (t > 0) {
return name.split(" ")[0] + " Transfer"
}
else {
return name.split(" ")[0]
}
}
/*
Model transfer 2 transfer - Model transfer 3 //Expected output
Model transfer transfer Transfer - Model transfer 3 //Expected output
Model transfertransfer Transfer Transfer - Model transfer 4 //Expected output
Model transfer - Model transfer //Expected output
Model - Model //Expected output
*/
console.log( renameNameOccurrence( "Model transfer 2 transfer" ))
console.log( renameNameOccurrence( "Model transfer transfer Transfer" ))
console.log( renameNameOccurrence( "Model transfer transfer Transfer Transfer" ))
console.log( renameNameOccurrence( "Model transfer" ))
console.log( renameNameOccurrence( "Model" ))
添加回答
举报