Home > Mobile >  issue with wrapping a array of signs with ^ sign
issue with wrapping a array of signs with ^ sign

Time:11-25

Here is a function to wrap an array of signs with ^ sign, and it works fine for string1, let's have a look:

function modifyAuto(string) {
    const allSigns = ['!!', '?!', '!?', '...', '..', '.', '?', '؟!', '!؟', '!', '؟', '،', '؛', ','];
    const str = allSigns.map(e => e.replace(/\?/g, '\\?').replace(/\./g, '\\.')).join('|');
    const regex = new RegExp(`\\s*(?:\\^\\s*)*(${str})\\s*(?:\\^\\s*)*`, 'g');
    return string.replace(regex, ' ^$1^ ');
}

const string1 = 'this is a text, right';
const string2 = 'this is a text, ^right^';

console.log('works fine :::', modifyAuto(string1)) 
console.log('one of the ^ signs removed :::', modifyAuto(string2))

as you see for a normal string1 the function works fine, but as you see in string2 if there is already a word wrapped with ^ close to a , sign for instance , one of the ^ will be removed.

the desired result for the string2 should be :

"this is a text ^,^ ^right^"

How would you fix this?

CodePudding user response:

Then only remove ^s that are immediately before/after the found match with

const regex = new RegExp(`\\s*\\^?(${str})\\^?\\s*`, 'g');

See the fixed demo:

function modifyAuto(string) {
    const allSigns = ['!!', '?!', '!?', '...', '..', '.', '?', '؟!', '!؟', '!', '؟', '،', '؛', ','];
    const str = allSigns.map(e => e.replace(/\?/g, '\\?').replace(/\./g, '\\.')).join('|');
    const regex = new RegExp(`\\s*\\^?(${str})\\^?\\s*`, 'g');
    return string.replace(regex, ' ^$1^ ');
}

const string1 = 'this is a text, right';
const string2 = 'this is a text, ^right^';

console.log('works fine :::', modifyAuto(string1)) 
console.log('one of the ^ signs removed :::', modifyAuto(string2))

  • Related