views:

358

answers:

2

Hi,

I need to remove the following format from the end of a string in javascript

1234, Australia

And only at the end of a string.

How would I do this?

+2  A: 

Ok, so I found out what I was doing wrong...

var a = '888 Welles St, Scoresby Victoria 3179, Australia'.replace('/\d{4}, Australia/', '');
alert(a);

I was surrounding the regex pattern in quotes. Which it apparently doesn't need. So this works:

var a = '888 Welles St, Scoresby Victoria 3179, Australia'.replace(/\d{4}, Australia/, ''); 
alert(a);
navitronic
If you want to make sure that the "xxxx, Australia" is only matched when it's at the end of the string, you'll have to add a dollar sign after "Australia": /\d{4}, Australia$/
Steve Harrison
You'd also want to add the /i switch to your Regex if different cases of the word "Australia" ("AustraLIA", "australia", etc.) creep into your text.
Kirtan
+2  A: 

Your solution is good.
I would add the $ so as not to replace anything unintentionally:

a = strVar.replace((/\d{4}, \w+$/,'');

Explanation from here:

/and$/ matches "and" in "land" but not "landing"

And you can even get a little more crazy by adding word boundaries:

a = strVar.replace((/\d{4}, \b\w+\b$/,'');
Adam Bernier
As far as I see, the word boundaries in your second regex are useless. A space followed by `\w` implies a word boundary already. The same goes for `\w` followed by `$`.
Geert
@Geert, you're absolutely right. I added word boundaries to demonstrate a possible way to make this regex useful in more general situations. As it stands, the regex is not particularly good at handling different inputs -- which is of course understood by the OP as he is using it for only this particular case. Your comment is much appreciated.
Adam Bernier