简体   繁体   English

根据输入设计自定义文件编号字符串

[英]Designing a custom file number string based on input

I really need your help with this since this goes well beyond my level of capability of javascript coding. 我真的需要您的帮助,因为这远远超出了我的javascript编码能力。

I'd like to design a function that would accomplish one of the following two scenarios: 我想设计一个函数来完成以下两种情况之一:

  1. If there is no dash and number at the end of the string var 'fileno', then rewrite the string fileno and add the dash and then the count at the end. 如果字符串var'fileno'的末尾没有破折号和数字,则重写字符串fileno并在其末尾添加破折号和计数。

    var fileno = 'test' var fileno ='测试'

    var c = 4 var c = 4

    fileno = 'test-4' fileno ='test-4'

  2. If there is already a dash and then a number at the end of the string, replace the dash-number with the new info below: 如果字符串中已经有破折号和数字,则将破折号替换为下面的新信息:

    var fileno = 'test-2' var fileno ='test-2'

    var c = 3 var c = 3

    fileno = 'test-3' fileno ='test-3'

You may use regular expression with String.prototype.replace() : 您可以将正则表达式与String.prototype.replace()

fileno = fileno.replace(/-\d+$|$/, '-' + c);

It literally means: replace -{number} or nothing at the end of the string with -{c} . 从字面上看,这意味着:用-{c}替换字符串末尾的-{number}什么也不替换。

 var c = 3; console.log( 'test'.replace(/-\\d+$|$/, '-' + c) ); console.log( 'test-4'.replace(/-\\d+$|$/, '-' + c) ); 

if(fileno[fileno.length - 2] === "-"){
  fileno = fileno.substr(0,-1) + c;
} else {
  fileno += "-" + c;
}

Just either append a new number if there is already a - in the second last position or append a new one. 如果在倒数第二个位置已经有- ,则追加一个新数字,或者追加一个新数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM