I tried to write a function to replace ampersands which are arround word in string with just single hashtag which will be at the beginning of word &word& => #word. And I did it, but after looking at my code I can tell that it’s kind of ugly, and also I need function that will return text to version with ampersands too. So, maybe someone can tell me how can I improve it? Maybe someone can provide version with regex?
const text = "&string& someText&string2& &string3& &string4&&string5&";
const replaceAmpersandsWithHashtag = (text: string) => {
const firstStep = text.replace(/\&/g, '#');
let occurenceOfHashtag = 0;
const secondStep = firstStep.split('').filter(char => {
if(char === '#') {
occurenceOfHashtag += 1 ;
return occurenceOfHashtag % 2 === 0 ? false : true;
}
return true
}).join('');
return secondStep
}
const replaceHashtagWithAmpersands = (text: string) => {
const firstStep = text.replace(/\#/g, '&');
let isLookingForNextAmpersand = false;
const secondStep = firstStep.split('').map((char, index) => {
if(char === '&') {
isLookingForNextAmpersand = true;
return char;
}
if(isLookingForNextAmpersand && firstStep.length === index + 1) {
isLookingForNextAmpersand = false;
return `${char}&`
}
if(isLookingForNextAmpersand && (firstStep.charAt(index + 1) === ' ' || firstStep.charAt(index + 1) === '&')) {
isLookingForNextAmpersand = false;
return `${char}&`
}
return char
}).join('');
return secondStep
}
const textWithHastags = replaceAmpersandsWithHashtag(text);
const againWithAmpersands = replaceHashtagWithAmpersands(textWithHastags);
// Should be "#string someText#string2 #string3 #string4#string5"
console.log(textWithHastags)
// Should be "&string& someText&string2& &string3& &string4&&string5&"
console.log(againWithAmpersands)
// Should be "true"
console.log(text === againWithAmpersands)
>Solution :
Use a capture group in the regexp to copy the word between the & to the replacement.
function replaceAmpersandsWithHashtag(string) {
return string.replace(/&(\w+)&/g, '#$1');
}
function replaceHashtagWithAmpersands(string) {
return string.replace(/#(\w+)/g, '&$1&');
}
const text = "&string& someText&string2& &string3& &string4&&string5&";
const textWithHastags = replaceAmpersandsWithHashtag(text);
const againWithAmpersands = replaceHashtagWithAmpersands(textWithHastags);
// Should be "#string someText#string2 #string3 #string4#string5"
console.log(textWithHastags)
// Should be "&string& someText&string2& &string3& &string4&&string5&"
console.log(againWithAmpersands)
// Should be "true"
console.log(text === againWithAmpersands)