【问题标题】:Join the string with same separator used to split使用用于拆分的相同分隔符加入字符串
【发布时间】:2020-04-27 02:07:46
【问题描述】:

我有一个字符串需要用正则表达式拆分以进行一些修改。

例如:

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

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

现在字符串已被+# 分割。 现在说在对数组中的项目进行了一些修改之后,我必须使用与拆分相同的分隔符加入数组,因此字符 +# 必须与之前的位置相同。

例如:如果我应用了一些修改字符串并加入。那应该就是了。

Hello001+Beutiful002#World003

我该怎么做?

【问题讨论】:

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

标签: javascript arrays regex string split


【解决方案1】:

在这种情况下不要使用 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);

【讨论】:

    【解决方案2】:

    您可以通过迭代拆分的值并检查部分来获取丢失的子字符串。

    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(''));

    【讨论】:

      【解决方案3】:

      当您将模式放入捕获组中时,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("")
      );

      【讨论】:

      • 谢谢,偶数位置的符号有帮助
      【解决方案4】:

      您可以通过查找字符串上发生匹配的索引来重新加入数组

      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);

      【讨论】:

        【解决方案5】:

        我的解决方案是获取拆分器,然后将它们保存到数组中并重新加入:

        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
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-12-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-04
          • 1970-01-01
          • 2019-05-08
          • 2020-01-07
          相关资源
          最近更新 更多