简体   繁体   中英

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 ( ' )?

You need to replace ' by nothing in that case. Currently you are replacing the whole string when it starts with a ' .

So

.replace(/'/g,'');

might work. Or

.replace(/^'|'$/g,'');

if you only want to replace those in the start and end.

This should work

otherSpecialId[0].trim().replace(/'/g, '')

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

This works

var str = "'234324234234234236548723adf83287942'";
var rep = str.replace(/'/g,"");
alert(rep);

http://jsfiddle.net/jasongennaro/qyHth/

The g tells it to be greedy... and replace every instance of ' .

replace(/'/g,"");

This replaces all [ ' ] with Empty String

'/g' is global flag and needed for replecement of all occurences not only the first one

Working Example JSFiddle

var input = "\"'234324234234234236548723adf83287942'\"";

alert("Before replace :  " + input);

input = input.replace(/'/g,"");

alert("Aftwer replace :  " + input);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM