'Typescript : Check for words in a string

There are many options in javascript, but are there any options in typescript to do the find words in a given string:

Eg:

For the list: ['Mr', 'Mrs', 'FM.', 'Sir'] and a string called 'Sir FM. Sam Manekshaw'. I have the words 'Sir' and 'FM.' present, hence needs to be assigned to a string and the remaining parts of the string assigned to another string. i.e:

a = Sir FM.
b = Sam Manekshaw

NOTE: It should validate only full words and not a substring.

UPDATE: What I tried:

var tempPrefixList = ['Mr', 'Mrs', 'FM.', 'Sir'];
var firstName = "Sir FM. Sam Manekshaw";

var prefixSearchExp = new RegExp(tempPrefixList.join("|"),"gi");
if(firstName && prefixSearchExp.test(firstName)) {
    console.log("Caught");
    var requestFirstNameSplit = firstName?.split(" ");
    console.log("Prefix: " + requestFirstNameSplit[0]);
    console.log("First name: " + requestFirstNameSplit[1]);
}

But this considers only if the name has one Prefix. And also, has only one name in firstName. Eg: Sir Sam. But doesn't work for the example I mentioned earlier.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source