Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
12.2k views
in Web Development by 37 41 48

I need to replace a part of my current URL with another string using JavaScript when clicking on the URL <A> tag in HTML.

The current URL is

https://mysite/ar/index.html

The desired URL should replace a part of the current string to be like

https://mysite/en/index.html

After changing the URL I need to set its value to <a> tag in HTML, How I can do that in JavaScript?


1 Answer

2 like 0 dislike
by 163 204 403
selected by
 
Best answer

Replace String in URL using JavaScript

To replace a string in the current page URL using JavaScript, you have to use the replace function with location.href as below

var url = location.href.replace('/ar/','/en');

Set <a> tag link in HTML using JavaScript

To set the new URL to <a> Link tag in HTML, try to do this

<html>
<head>
<script>
function replaceString()
    {
         return location.href=location.href.replace('/ar/','/en/') ;
    }
</script>
</head
<body>
    <a id="language" href="#" onclick="replaceString()">debug</a>
</body>
</html>

Set <a> tag link in HTML using JQuery

You can also use JQuery to set the href parameter in <a> tag as below

$("#language").on('click', function() {
  window.location = location.href.replace('/ar/','/en/') ;
});
by 37 41 48
0 0
Thank you man for this quick and helpful answer
If you don’t ask, the answer is always NO!
...