【问题标题】:Adding dashes at certain positions in a string (Javascript)在字符串中的某些位置添加破折号(Javascript)
【发布时间】:2021-07-01 03:07:12
【问题描述】:

我创建了一个函数,可以在每个给定字符串的特定位置添加破折号 (-)。

const addDashes = (string) => {
   let splittedString;
   splittedString = string.split('');
   splittedString.splice(3, 0, "-")
   splittedString.splice(10, 0, "-")
   return splittedString.join("");
}

小提琴 -> https://jsfiddle.net/src87u6e/

所以问题是应该在前 3 个字母之后添加一个破折号,然后在其他前 6 个数字之后添加一个破折号。

我想知道是否有比这更好/更清洁的解决方案。

谢谢!

【问题讨论】:

    标签: javascript arrays string algorithm


    【解决方案1】:

    const addDashes = (string) => string.slice(0, 3) + "-" + string.slice(3, 9) + "-" + string.slice(9);
    
    console.log(addDashes("ABC0000000000001"))

    【讨论】:

    • 更好;))
    【解决方案2】:

    当然,只需使用正则表达式:

    const addDashes = str => str.replace(/^(.{3})(.{6})/, '$1-$2-')
    console.log(addDashes('0123456789abcd'))

    模式^(.{3})(.{6}) 在字符串开头捕获 3 个字符,然后是 6 个字符 (^),然后用第一个捕获字符 ($1) 替换整个内容(即 9 个字符),破折号,第二个,破折号。

    Reference

    使用数组实现更通用的解决方案更简洁:

    // insert a character at given positions of the string
    const insertAt = (str, what, where) => [...str]
        .map((c, n) => where.includes(n) ? what + c : c)
        .join('');
    
    console.log(insertAt('0123456789abcd', '-', [3, 9]))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      相关资源
      最近更新 更多