Looking to find a way to remove a part of the url and then put it all back together.
For example if site is https://example.com/ko/xxx/xxxx
I want to remove the 'ko' and it be https://example.com/xxx/xxxx
I also think I need to loop through the items as it's checking if the link has the classname `int-tooltip'
var ko_link_url = $(".int-tooltip");
var ko_link_url_href = ko_link_url.attr("href");
var split = ko_link_url_href.split("/");
ko_link_url_href = ko_link_url_href.split("/");
ko_link_url_href = ko_link_url_href[3];
if (ko_link_url_href == "ko") {
ko_link_url_href.replace(split[3], "");
}
CodePudding user response:
I think you're making this a bit more complicated than it needs to be - just search for https://example.com/ko/
and replace with https://example.com/
. Loop through elements with .each
.
$('.int-tooltip').each(function() {
this.href = this.href.replace('https://example.com/ko/', 'https://example.com/');
});
CodePudding user response:
If I understand you correctly, you want to find all the anchors with class int-tooltip
and href
starting with https://example.com/ko/
and remove the ko
part.
$("a[href^='https://example.com/ko/'].int-tooltip").attr("href", (_, href) =>
href.replace("https://example.com/ko/", "https://example.com/")
);
$("a[href^='https://example.com/ko/'].int-tooltip").attr("href", (_, href) =>
href.replace("https://example.com/ko/", "https://example.com/")
);
$("pre").text($("p").html());
p { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<p>
<a href="https://example.com/ko/xxx/xxxx">No class on this one</a>
<a href="https://example.com/ko/xxx/xxxx" >Change this one</a>
<a href="https://example.com/ok/xxx/xxxx" >No "ko"</a>
</p>
<pre></pre>
CodePudding user response:
Consider the following.
$(function() {
var ko_link_url_href = "https://example.com/ko/xxx/xxxx";
var urlParts = ko_link_url_href.split("/");
$.each(urlParts, function(i, el) {
if (el == "ko") {
urlParts.splice(i, 1);
}
});
var link_url_href = urlParts.join("/");
console.log(link_url_href);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This splits the URL into an array, based on the /
character. You can then iterate each part of the array and check the value. If it is found, you can use .splice()
to remove it from the array. You can join the parts back with /
character.