Join the string with same separator used to split

十年热恋 提交于 2020-12-26 07:13:04

问题


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

eg:

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

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

Now the string has been split with + or #. Now say after applying some modification to the items in the array, I have to join the array using the same separator that used to split, so the character + and # has to be in the same position as before.

eg: if i applied some modification string and joined. Then it should be.

Hello001+Beutiful002#World003

How can i do this?


回答1:


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



回答2:


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



回答3:


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



回答4:


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
}



回答5:


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


来源:https://stackoverflow.com/questions/59664482/join-the-string-with-same-separator-used-to-split

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!