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.
content:string[] = languagesKnown..split('\n')
gives me a string array, But I want to see if something is set to it or if it is empty like above.
try using split:
const examples = ['Mother-Tongue: Spanish OtherLanguages: English Major: German', 'Mother-Tongue: OtherLanguages: English Major: German']
const values = examples.map(string => string.split(/[a-zA-Z-]*:/).slice(1))
for (value of values) {
console.log(value[0].replace(/ /g, '') !== '')
}
With a regex you can easily find if there is a Mother Tongue and get its value.
let languagesKnown1 = 'Mother-Tongue : Spanish OtherLanguages: English Major: German';
let languagesKnown2 = 'Mother-Tongue: OtherLanguages: English Major: German';
function getMotherTongue(languagesKnown){
let regexMatch = languagesKnown.match(/Mother-Tongue : \w+/)
if(regexMatch != null && regexMatch.length > 0)
return regexMatch[0].split(":")[1].trim()
return "No Mother Tongue!"
}
console.log(getMotherTongue(languagesKnown1))
console.log(getMotherTongue(languagesKnown2))
Try to split the string into an array of strings with : as the delimitier character.
The only problem could be the nonuniform formatting. So a solution could be counting the whitespaces. If there is more than 1 whitespace after a colon -> empty value.