czmarc czmarc - 19 days ago 6
Javascript Question

angular: filter to replace and complete relative <a href="/"> paths

I'm new to angular and I'm struggling to replace relative href paths inside my text.

For example purposes, I have the following controller/scope/html/filter:

$scope.text = 'Here you can find the best <a href="/shoes/sport">sport shoes</a>, <a href="/shoes/classic">classic shoes</a> and <a href="/socks/sale">socks</a>. If not, you can <a href="http://www.google.com">google</a> it.';

<p ng-bind-html="text | parseUrlFilter"></p>


I tried to create a filter that search for all relative urls and replace with the complete path url (eg: http://www.example.com/shoes/sport, http://www.example.com/shoes/classic, http://www.example.com/socks/sale):

app.filter('parseUrlFilter', function() {

var urlPattern1 = 'href="/shoes/';
var urlPattern2 = 'href="/socks/';

return function(text) {


angular.forEach(text.match(urlPattern1), function(url) {
url = url.replace('href="','');
text = text.replace(url, 'http://www.example.com' + url);
});

angular.forEach(text.match(urlPattern2), function(url) {
url = url.replace('href="','');
text = text.replace(url, 'http://www.example.com' + url);
});

return text;
};

})


However, my filter replace only the first case (http://www.example.com/shoes/sport) for each pattern.

Does anyone know how I can make it work fine and replace for all matches and patterns OR is there any other clever/smarter way to get what I need?

PS: this angular project is an Ionic platform (mobile app) and I'm retrieving data (text + links) from a database that is shared with a desktop version (php), which usually inserts these relative paths. Thus I need to complete them, otherwise many links will be broken in my mobile app.

Thanks for any help!

Answer

You can try using a regular expression. Something like that:

var str = 'Here you can find the best <a href="/shoes/sport">sport shoes</a>, <a href="/shoes/classic">classic shoes</a> and <a href="/socks/sale">socks</a>. If not, you can <a href="http://www.google.com">google</a> it.';
var res = str.replace(/href=\"\//g, "href=\"http://www.example.com/");

The 'g' in regular expressions is a global replace.