Split and replace href
I'm trying to break and replace the href with a function. The code is simple and straightforward:
Html
<a href="http://nu.nl">nu.nl</a>
Jquery
$(document).ready(function () {
function rep() {
href = $('a').attr('href');
url = href.split('/');
href.replace(url[2], 'cnn.com');
}
rep()
});
As you can see, I am calling the function on the finished document. I tried "prop" instead of attr with no luck. What am I doing wrong? Example: JsFiddle
+3
source to share
2 answers
You are not using what returns replace
. If you want to change the href on an element a
, you can change
href.replace(url[2], 'cnn.com');
to
$('a').attr('href', href.replace(url[2], 'cnn.com'));
Now, suppose you can have multiple elements a
, I would suggest replacing all your code with
$('a').attr('href', function(_, href){
url = href.split('/');
return href.replace(url[2], 'cnn.com');
});
If you prefer, you can also avoid the splitting with a regex:
$('a').attr('href', function(_, href){
return href.replace(/\/\/[^\/]+/, '//cnn.com')
});
+5
source to share
You don't need to define your function inside the document.ready document
function rep(myURL, replaceWith) {
var arr = myURL.split('/');
myURL = myURL.replace(arr[2], replaceWith);
return myURL;
}
$(document).ready(function () {
$('a').attr('href', rep(
$('a').attr('href'),
'cnn.com'
)
);
});
+1
source to share