How to get first 2 characters in a comma separated string. It should be in capital letter and add _ (underscore) between the 2 characters using Javascript?
countries: "Afghanistan, Albania, Germany"
And I want output as below:
AF_AL_GE
How can I get this output ?
You can split the string by ", ", map through it and get the first two characters with slice, join it all with an underscore, then make it uppercase:
const countries = "Afghanistan, Albania, Germany"
const output = countries
.split(", ")
.map(i => i.slice(0, 2))
.join("_")
.toUpperCase()
console.log(output)
You can split string to array by ", ". Next map the subsisting and convert it to uppercase, Finally join the array with "_"
const countries = "Afghanistan, Albania, Germany";
const countryCodeString = countries
.split(", ")
.map(country => country.substring(0, 2).toUpperCase())
.join("_");
console.log(countryCodeString);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With