如何将此字符串20346017621转换为20-34601762-1

时间:2019-02-05 17:56:17

标签: node.js

我们如何在节点上设置功能

在前两个数字和最后一个数字之后,我们要添加-连字符

可以获取字符串 像这样:xxzzzzzzzzzzx

并转换为此:xx-zzzzzzzz-x

example of what we need   
function tranformer (xxzzzzzzzzx){
NOT SURE HOW TO SOLVE THIS
return xx-zzzzzzzz-x
}

非常感谢您!

不知道如何完成这项任务。

2 个答案:

答案 0 :(得分:0)

function tranformer(st) {
    let newStr = ""
    for (let i = 0; i < st.length; i++) {
        if (i === 2 || i === st.length - 1) {
            newStr += "-"
        }
        newStr += st[i]
    }
    return newStr
}

使用切片

let first = st.slice(0, 2)
let middle = st.slice(2, -1)
let last = st.slice(-1)
newStr = first + "-" + middle + "-" + last
console.log(newStr)

答案 1 :(得分:0)

首先,我将字符串分解为数组,然后使用splice命令在指定位置插入-字符:

let str = "xxzzzzzzzzx";

str = str.split('');

str.splice(2, 0, '-');  // insert - at pos 2
str.splice(str.length - 1, 0, '-');  // insert - at pos -1

console.log(str.join(''))  //-> xx-zzzzzzzz-x