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