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
in Web Development by 35 40 47

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


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


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 151 169 345
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

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

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 35 40 47
0 0
Thank you man for this quick and helpful answer
If you don’t ask, the answer is always NO!