CAK
CAK

Reputation: 423

Regular expression for extracting the city name from string pattern

I wanted to extract the city name from the following example patterns.

  1. Philadelphia.json
  2. Philadelphia
  3. Washington D.C..json
  4. Upstate New York.json

Only one regex. should be suitable for all the above patterns to extract the city name.

.json in the end is optional. It will only come if it is the API call, in case of HTML request it will not come.

The output is expected as follows:

  1. Philadelphia
  2. Philadelphia
  3. Washington D.C.
  4. Upstate New York

Please help me on this.

Upvotes: 1

Views: 1897

Answers (5)

vks
vks

Reputation: 67998

^([A-Z][\s\w.,-]+?)(?=\.json|$)

Try this .See demo.

http://regex101.com/r/lS5tT3/38

Upvotes: 1

Mr_Green
Mr_Green

Reputation: 41872

Try this:

Without Regex:

yourString = (yourString.lastIndexOf(".json") > -1)?yourString.slice(0,-5):yourString;

With Regex:

yourString = yourString.replace(/\.json$/,"");

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174874

You could try the below regex to match only the city names which are present at the start.

^[A-Z][a-z]+(?: [A-Z]\.[A-Z]\.?|(?: [A-Z][a-z]+)*)

DEMO

OR

^[A-Z][a-z]+[ .A-Za-z]*?(?=\.json|$)

DEMO

Upvotes: 1

Abdul Jabbar
Abdul Jabbar

Reputation: 2573

If regex isn't necessary then this simple one line function will do the work for you:

function removeJson(s){
        return s.replace('.json','');
}
alert(removeJson("Philadelphia.json")); //"Philadelphia"
alert(removeJson("Philadelphia"));      //"Philadelphia"

Pass any string to it and you will have .json removed if its there.

See the DEMO here

Upvotes: 0

user1933888
user1933888

Reputation: 3037

You can simply do the following:

String test = "Philadelphia.json";      // or any other input string
    String replaced = test.replace(".json", "");

Upvotes: 0

Related Questions