Home > database >  JavaScript - How to get the line after the second comma
JavaScript - How to get the line after the second comma

Time:11-03

I have a certain line I want to get from this line the word "USA" which is after the second comma, how can I get it? I have a lot of such lines, I need to get a certain word that is after the second comma

let x = `Addr: Miami Beach, FL 321, USA, Distance: 7642 mi`;

CodePudding user response:

Simply splitting the string on commas and accessing the element after the 2nd one should be enough. As long as the line does indeed contain enough commas you can do:

const x = `Addr: Miami Beach, FL 321, USA, Distance: 7642 mi`;
const result = x.split(",")[2].trim();

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Please note i called String.prototype.trim() function simply to remove whitespace from the beginning of a string.

CodePudding user response:

You can split the string and get the second index from the value. Use optional chaining .? to avoid the error.

let x = `Addr: Miami Beach, FL 321, USA, Distance: 7642 mi`;
let value = x.split(',')?.[2]
console.log(value)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

This will return undefined if there is no value after the second comma (,).

If you want to use trim() then you can add this line-

 value = value ? value.trim() : '';
  • Related