Skip to content
Advertisement

Why does this regex replace remove a symbol at the start, but not at the end?

I am trying to remove the apostrophes from this string: "'234324234234234236548723adf83287942'".

I am trying to use this:

var specialId = otherSpecialId[0].trim().replace(/^[']*$/,'');

to try and get "234324234234234236548723adf83287942".

But I can’t seem to crack it. How do I remove the apostrophes (')?

Advertisement

Answer

Just use ' on it’s own with the global modifier:

var specialId = otherSpecialId[0].trim().replace(/'/g,'');

Alternatively, if the quotes are always at the start and end, you don’t need to use a regex at all:

var specialId = otherSpecialId[0].trim().slice(1, -1);

‘Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.’ — Jamie Zawinski

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement