Reputation: 423
I wanted to extract the city name from the following example patterns.
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:
Please help me on this.
Upvotes: 1
Views: 1897
Reputation: 67998
^([A-Z][\s\w.,-]+?)(?=\.json|$)
Try this .See demo.
http://regex101.com/r/lS5tT3/38
Upvotes: 1
Reputation: 41872
Try this:
yourString = (yourString.lastIndexOf(".json") > -1)?yourString.slice(0,-5):yourString;
yourString = yourString.replace(/\.json$/,"");
Upvotes: 1
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]+)*)
OR
^[A-Z][a-z]+[ .A-Za-z]*?(?=\.json|$)
Upvotes: 1
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.
Upvotes: 0
Reputation: 3037
You can simply do the following:
String test = "Philadelphia.json"; // or any other input string
String replaced = test.replace(".json", "");
Upvotes: 0