【问题标题】:Look for characters and if exists increment 1查找字符,如果存在则增加 1
【发布时间】:2020-08-13 10:57:14
【问题描述】:

我正在尝试使用 javascript 创建一个文件夹,但在此之前我需要检查该文件夹是否存在以及它是否确实将数字增加了 1。

这是我的输入名称:ABC 集团

我希望 javascript 删除“The”并将其移至末尾,然后最后添加一个基于前 4 个字符后跟一个数字的代码。如果目录中不存在前 4 个字符,则它将从 01 开始并从那里递增。

这是我要输出的内容:

即ABC 集团 (ABCG01)

我是 javascript 新手,但到目前为止,我已经弄清楚了除了我坚持的数字部分之外的所有事情。

这是我的代码:

var clientName = "the ABC company"; 

// Change Case - START
const toCapitaliseCase = (phrase) => {
return phrase
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
};

let capitalise = toCapitaliseCase(clientName);
// Change Case - END
// Format Client Name if starts with 'The' - START)

if (capitalise.startsWith('The ')) {  
let words = capitalise.split(' ');
let the = words[0];
let theSlice = capitalise.slice(4);
let comma = ', ';
let name = theSlice.concat('', comma, the);
let name2 = name.replace(/[^0-9a-zA-Z]/g, "");
let theSlice2 = name2.slice(0,4);
var upper = theSlice2.toUpperCase(); // output - "i am a crazy string, make me normal!"
let numbecccr = '101';
let theSlice3 = numbecccr.slice(1);



let FullCompiledName = theSlice.concat('', comma, the, ' (',upper, theSlice3, ')');

console.log(FullCompiledName);
// Format Client Name - START

}

【问题讨论】:

  • 我收到“ABC Company, The (ABCC01)”,有什么问题?
  • 当我添加另一个名为 I.e. ABC Corp,4 位数代码也将是(ABCC01),因为该代码已经存在,我需要它是(ABCC02)。我需要锻炼如何查看 ABBC01、2、3、4、5 等是否存在并增加 1
  • 你需要检查文件夹是否存在,如果是,你应该切片最后一个字符并使用 parseInt 然后在这个数字上加 1

标签: javascript javascriptcore


【解决方案1】:

我将您的代码放入一个函数中,每次调用该函数时,我都会在其中计数。

var clientName = "the ABC company"; 

function createName(clientName) {
    this.number = this.number || 0;
    // Change Case - START
    const toCapitaliseCase = (phrase) => {
        return phrase
        .split(' ')
        .map(word => word.charAt(0).toUpperCase() + word.slice(1))
        .join(' ');
    };

    let capitalise = toCapitaliseCase(clientName);
    // Change Case - END
    // Format Client Name if starts with 'The' - START)

    if (capitalise.startsWith('The ')) {  
        let words = capitalise.split(' ');
        let the = words[0];
        let theSlice = capitalise.slice(4);
        let comma = ', ';
        let name = theSlice.concat('', comma, the);
        let name2 = name.replace(/[^0-9a-zA-Z]/g, "");
        let theSlice2 = name2.slice(0,4);
        var upper = theSlice2.toUpperCase(); // output - "i am a crazy string, make me normal!"
        this.number++;
        let num = this.number;
        if(('' + num).length == 1) {
            num = '0' + num;
        }



        let FullCompiledName = theSlice.concat('', comma, the, ' (',upper, num, ')');

        return FullCompiledName;
    }
}

console.log(createName(clientName));
console.log(createName(clientName));

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多