使用与拆分相同的分隔符连接字符串

6
我有一个字符串需要用正则表达式分割,以应用一些修改。
例如:
const str = "Hello+Beautiful#World";
const splited = str.split(/[\+#]/)

// ["Hello", "Beautiful", "World"]

现在这个字符串已经被拆分为+#。 现在假设在数组中对项目进行了一些修改,我必须使用相同的分隔符连接数组,因此字符+#必须与之前相同的位置。

例如:如果我应用了一些修改字符串并连接。 那么它应该是。
Hello001+Beutiful002#World003

这该怎么做?

这是一个模式吗,就像我们必须在每个单词的末尾添加一个计数器吗? 如果这是一个模式,最好不要拆分单词,而是创建一个新字符串。 - Aashutosh Rathi
分隔符可以是多字符字符串吗? - Wiktor Stribiżew
@AashutoshRathi你可以忽略计数器,它可以是任何修改。 - Aslam
@WiktorStribiżew 是的,我可以假设它将是单个字符。 - Aslam
5个回答

5
当您将一个模式放置在捕获组中时,split 将返回匹配的分隔符作为偶数数组项。因此,您只需修改奇数项即可:

var counter=1;
var str = "Hello+Beautiful#World";
console.log(
  str.split(/([+#])/).map(function(el, index){
    return el + (index % 2 === 0 ? (counter++ + "").padStart(3, '0') : '');
  }).join("")
);


1
谢谢,偶数位置上的符号有所帮助。 - Aslam

2
在这种情况下不要使用 split 和 join。使用 String.replace(),并返回修改后的字符串:

const str = "Hello+Beautiful#World";

let counter = 1;
const result = str.replace(/[^\+#]+/g, m =>
  `${m.trim()}${String(counter++).padStart(3, '0')}`
);

console.log(result);

另一种选择是使用前瞻将特殊字符分割,映射这些项,并用空字符串连接起来。然而,这种方法可能并不适用于所有情况。

const str = "Hello+Beautiful#World";

let counter = 1;
const result = str.split(/(?=[+#])/)
  .map(s => `${s.trim()}${String(counter++).padStart(3, '0')}`)
  .join('')

console.log(result);


1
你可以通过迭代拆分后的值并检查各个部分来获取缺失的子字符串。

var string = "Hello++#+Beautiful#World",
    splitted = string.split(/[\+#]+/),
    start = 0,
    symbols = splitted.map((s, i, { [i + 1]: next }) => {
        var index = string.indexOf(next, start += s.length);
        if (index !== -1) {
            var sub = string.slice(start, index);
            start = index;
            return sub;
        }
        return '';
    });

console.log(symbols);
console.log(splitted.map((s, i) => s + symbols[i]).join(''));


1
我的解决方案是获取分隔符,然后将它们保存到一个数组中并重新连接:
function splitAndRejoin(){
    const str = "Hello+Beautiful#World";
    const splited = str.split(/[\+#]/);
    var spliterCharacter = [];
    for(var i = 0; i < str.length; i++){
        if(str[i] == "+" || str[i] == "#"){
            spliterCharacter.push(str[i]);
        }
    }
    var rejoin = "";
    for (i = 0; i <= spliterCharacter.length; i++) {
        if(i< spliterCharacter.length)
            rejoin += splited[i] + spliterCharacter[i];
        else
            rejoin += splited[i];
    }
    console.log(splited);
    console.log(spliterCharacter);
    console.log(rejoin); // Result
}

0
你可以通过找到字符串匹配发生的索引来重新连接数组。

const str = "Hello+Beautiful#World";
const regex = /[\+#]/g;
const splited = str.split(regex);
console.log(splited);


//join
let x = '';
let i=0;
while ((match = regex.exec(str)) != null) {
    x = x + splited[i] + "00" + (i+1) + str[match.index];
    i++;
}
x = x + splited[splited.length-1] + "00" + (i+1);
console.log(x);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接