0

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?

3
  • 2
    Can you explain a bit more. Do you mean you need to remove a 4-digit number, followed by a comma, followed by a country from a string? Is the string always a fixed length? That is, does the 4-digit code always start at the same position? Commented Jul 10, 2009 at 5:35
  • Ummm, you have a string like this "some-long-string 1234, Australia", and you want to remove this "1234, Australia" from the last, am I correct? Commented Jul 10, 2009 at 5:36
  • Yes you are correct Kirtan, obviously the 1234 can be any 4 digit number. Commented Jul 10, 2009 at 5:38

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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$/
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.
2

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$/,'');

2 Comments

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, 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.