Regular indexOf only takes a string parameter, no regular expressions.
const arr = ["Title", "First", "Last", "Email", "↵"];
arr.indexOf('\u21b5'); // 4
To use regular expressions, you habe to use the find
method. Note that for Java-/Typescript to parse the unicode character in a regular expression, you need to use the u
flag - See also this, taken from this answer.
const char = arr.find(item => /\u{21b5}/u.test(item));
if (char) {
result = arr.indexOf(char); // 4
}
You can also write a custom RegEx-enabled indexOf function:
function regExIndexOf(array: string[], term: RegExp, start = 0): number {
let result = -1;
array.forEach((item, index) => {
if (result === -1 && index >= start && term.test(item)) {
result = index;
}
});
return result;
}
regExIndexOf(["Title", "First", "Last", "Email", "↵"], new RegExp('Title')); // 0
regExIndexOf(["Title", "First", "Last", "Email", "↵"], new RegExp('Title'), 1); // -1
regExIndexOf(["Title", "First", "Last", "Email", "↵"], new RegExp('\u{21b5}', 'u')); //4
See on Typescript Playground