I have people addresses in string, what I want to do is extract city and state names from these address and store rest of the string as address. problem is I don't have any idea about how long the addresses are.
for example:
let address1 = "Akshardham Temple, Vidyut Nagar, Vaishali Nagar, Chitrakoot, Jaipur, Rajasthan"
let address2 = "Statue of Unity, Statue of Unity Road, Kevadia, Gujarat"
// and some might be just this
let address3 = "New Delhi, Delhi"
what I want is however long string is I want to extract last two entire words(state and city) and rest in another variable.
CodePudding user response:
First split the string by a comma:
const arr = address1.split(',');
This will give you an array of strings, e.g. ["Akshardham Temple", " Vidyut Nagar", " Vaishali Nagar", " Chitrakoot", " Jaipur", " Rajasthan"]
Then you can slice off the last 2 elements of the array:
const [city, state] = arr.slice(-2)
CodePudding user response:
As you say, you have to split the strings. If you want only whole words, it makes sense to use the space character as a separator.
const parts = address1.split(" ");
Now you have to access the last element and the second last element. Remember that length
is always one greater than the last index.
const lastWort = parts[parts.length-1];
const secondLastWort = parts[parts.length-2];
If you are bothered by the commas in the result, you can remove them first.
address1 = address1.replaceAll(",", "");
All together:
let address1 = "Akshardham Temple, Vidyut Nagar, Vaishali Nagar, Chitrakoot, Jaipur, Rajasthan";
address1 = address1.replaceAll(",", "");
const parts = address1.split(" ");
const lastWort = parts[parts.length-1];
const secondLastWort = parts[parts.length-2];
console.log(lastWort);
console.log(secondLastWort);
CodePudding user response:
You can use split
and splice
. The returned elements would need a call to trim()
so to avoid optional white space is dangling around the extracted words:
function splitAddress(s) {
let parts = s.split(",");
let [city, state] = parts.splice(-2).map(s => s.trim());
return { address: parts.join(","), city, state };
}
let tests = [
"Akshardham Temple, Vidyut Nagar, Vaishali Nagar, Chitrakoot, Jaipur, Rajasthan",
"Statue of Unity, Statue of Unity Road, Kevadia, Gujarat",
"New Delhi, Delhi"
];
for (let test of tests) {
console.log(splitAddress(test));
}