Join the string with same separator used to split

后端 未结 5 1243
执笔经年
执笔经年 2021-01-19 15:40

I have a string that need to be split with a regular expression for applying some modifications.

eg:

const str = \"Hello+Beautiful#World\";
const spl         


        
相关标签:
5条回答
  • 2021-01-19 16:22

    My solution is to get the splitters then save them into an array and rejoin:

    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 讨论(0)
  • 2021-01-19 16:26

    Don't use split and join in this case. Use String.replace(), and return the modified strings:

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

    Another option, which might not fit all cases, is to split before the special characters using a lookahead, map the items, and join with an empty string:

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

    0 讨论(0)
  • 2021-01-19 16:40

    you can rejoin the array by finding the indexes that where the matching happened on the string

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

    0 讨论(0)
  • 2021-01-19 16:41

    You could get the missing substrings by iterating the splitted value and check the parts.

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

    0 讨论(0)
  • 2021-01-19 16:42

    When you place a pattern inside a capturing group, split will return the matched delimiters as even array items. So, all you need to do is modify the odd items:

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

    0 讨论(0)
提交回复
热议问题