Gabe
Gabe

Reputation: 6347

Replace phone number in plain text with anchors in Javascript

How can I manipulate a string to add anchors in place of phone numbers?

More in details..

I have as input a string like this:

"Something went wrong. Please call us on 01 123 456 789 or 01 987 654 321."

I want as output:

"Something went wrong. Please call us on <a href="tel:01123456789">01 123 456 789</a> or <a href="tel:01987654321">01 987654321</a>."

(note that there could be any amount of phone numbers and that the spaces between numbers in the actual content could be there or not)

How can I achieve that in Javascript?

Upvotes: 0

Views: 306

Answers (1)

zruF
zruF

Reputation: 50

You can simply do that with Regex.

const input = "Something went wrong. Please call us on 01 123 456 789 or 01 987 654 321."
    
console.log(input.replace(/(\d\s*){5,}\d/g, x=>"<a href='tel:" + x.replace(/\s/g,"") + "'>" + x.trim() + "</a>"));

Upvotes: 1

Related Questions