detect and build links in a more concise manner

The original function would remove the space following the last word before the link. The issue can be resolved by using a more precise regex filter.