Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first 2 characters in a comma separated string - Javascript

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 ?

like image 398
userrj_vj_051620 Avatar asked May 19 '26 10:05

userrj_vj_051620


2 Answers

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)
like image 102
code Avatar answered May 22 '26 02:05

code


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);
like image 44
protob Avatar answered May 22 '26 02:05

protob