You can use \1 to ensure the use of the same character as in a capture group.
Thus, define some "limiters" at the beginning of the string, and at the end use \1 to make sure you have the same:
var testes = [
'!abba!', '?abba?', '"ab ba"', "'abba'", 'xabbax', '!eu vou falhar?'
];
function filtro(str) {
var match = str.match(/([!?'"x])(.*)(\1)/);
if (!match) return '';
return match[2];
}
console.log(testes.map(filtro));
In cases where you want to use pairs of symbols to open and close a text region, such as {}, () or <> this could be done:
const testes = [
'(abba)', '!eu vou falhar?', '{abba}', '<A>'
];
const separadores = ['{}', '\\(\\)', '<>'].map(char => {
const abertura = char.slice(0, char.length / 2);
const fecho = char.slice(char.length / 2);
return `(${abertura})([^${fecho}]+)(${fecho})`
}).join('|');
console.log(separadores)
const regex = new RegExp(separadores);
function filtro(str) {
var match = str.match(regex);
match = match && match.filter(Boolean);
if (!match) return '';
return match[2];
}
console.log(testes.map(filtro));
But
{and}are not the same character if it were{asdasd{would be easy. You need to create a function that compares theunicode. How many possible pairs will you use?– Sergio
Yes really, it was just a bad example I used. What if the characters were
"and'? - How the function you mentioned would work?– relaxeaza
I don’t see why the example is bad, I easily imagine cases where this is useful. Regarding the question
'/", you mean at the beginning you would have"and in the end'or would it be the same at the beginning and end? (and you saw my question: "How many possible pairs will you use?")– Sergio
I say bad example in order of simplicity to question. If at first it is
", should end with the same, and the same to'. Never starting with"and ending with'. I’ll use 5 pairs.– relaxeaza