Reputation: 77
Problem
I have some strings containing this symbol "#" and I want to get numbers after this symbol. For example:
A) Lorem Ipsum #1234 --> #1234
B) Lorem #234 Ipsum Dolor --> #234
What I tried
getTicketID(title: string): string {
const re = /#(\d+)/g;
return title.match(re);
}
but it doesn't work because I can't return a string:
Type 'RegExpMatchArray' is not assignable to type 'string'.
Upvotes: 1
Views: 1846
Reputation: 73251
You should simply return the first capturing group only. Additionally you can check for a match, and return a default value in case of no match, like an empty string or whatever you prefer.
const s = "Lorem #234 Ipsum Dolor";
function getTicketID(title: string): string {
const m = title.match(/#(\d+)/);
return m ? m[1] : "default value";
}
console.log(getTicketID(s));
Upvotes: 0
Reputation: 1266
It is returning array. you change like this
getTicketID(title: string): string[] {
const re = /#(\d+)/g;
return title.match(re);
}
then print the array
this.getTicketID(this.data).forEach(value=>console.log(value));
Upvotes: 1