Home > OS >  Get the value from a string as key value pair
Get the value from a string as key value pair

Time:07-08

I have a string that looks like this. Thi string is taken from a file where each of the keys are in different lines.

languagesKnown = 'Mother-Tongue : Spanish OtherLanguages: English Major: German' 

It can also look like

languagesKnown = 'Mother-Tongue:   OtherLanguages: English Major: German' 

I want to check which value is set to Mother-Tongue.

languagesKnown.include('Mother-Tongue') gives me a boolean, But I want to see if something is set to it or if it is empty like above.

CodePudding user response:

How about using split?

const languagesKnown = 'Mother-Tongue : Spanish OtherLanguages: English Major: German';

const noMotherTongue = 'Mother-Tongue:   OtherLanguages: English Major: German'

function hasMotherTongue(input ) {
  return input.split("OtherLanguages")[0].split(" : ").length > 1
}

console.log(hasMotherTongue(languagesKnown))
console.log(hasMotherTongue(noMotherTongue))

CodePudding user response:

Try to split the string into an array of strings with : as the delimitier character.

  • Related