Reputation: 102
I am new to Regular Expressions and I have been racking my head for hours to solve this
let text = "My twitter handle is @emmy, I follow @jo and @pe"
I need to replace @emmy with <a href="https://twitter.com/emmy">@emmy</a>
, likewise anyother string that starts with @ in the string.
Here is something I came up with from searching the internet and reading the docs on MDN
function linkify(text) {
let regex = /(?:^|\W)@(\w+)(?!\w)/g;
return text.replace(regex, function(handle) {
return `<a href="https://twitter.com/${handle.slice(1)}>${handle}</a>`;
})
}
The problem with this solution is that sometimes it omits some text, for example Earlier this week, @emmy featured the best student and dedicated to Earlier this week,
Any input towards a solution will be well appreciated.
Upvotes: 0
Views: 41
Reputation: 163332
If you want to use replace and specify a function as the second parameter, you could use 3 capturing groups to capture the match in front of the @
, the @
itself and the name.
In the function add 3 parameters which will correspond to the capturing groups.Then you could use those parameters in the replacement:
(^|\W)(@)(\w+)(?!\w)
let text = "My twitter handle is @emmy, I follow @jo and @pe";
function linkify(text) {
let regex = /(^|\W)(@)(\w+)(?!\w)/g;
return text.replace(regex, function(handle, p1, p2, p3) {
return `${p1}<a href="https://twitter.com/${p3}>${p2}${p3}</a>`;
});
};
console.log(linkify(text));
Upvotes: 1
Reputation: 147166
I don't think you need a callback for this problem, a straight replace should work:
let text = "My twitter handle is @emmy, I follow @jo and @pe";
console.log(text.replace(/(^|\W)@(\w+)\b/g, '$1<a href="https://twitter.com/$2">@$2</a>'));
Upvotes: 1