0

I have a url that looks something like this:

https://url.com/a b c

which is as expected. When the user clicks on this however, it redirects to the wrong link because the link actually has underscores instead of spaces in its url. is there any way to edit this url so that right before the url is clicked, the spaces turn into underscores? The url would look like so:

https://url.com/a_b_c when the user clicks it instead of what was above. Below is my attempt:

<a target="_blank" style="font-size: 9px" href="https://url.com/{{label}}">[Details]</a>

where label is equal to a b c. I tried the following:

<a target="_blank" style="font-size: 9px" href="https://url.com/{{label.replace(" ", "_")}}">[Details]</a>

so that a b c would turn into a_b_c but that didn't seem to work because the curly braces can't actually execute the replace function. Any help would be appreciated. If possible, I would also want to append some text to the end of this newly replaced label so it would look like: a_b_c_new_text Thanks!

user1871869
  • 3,317
  • 13
  • 56
  • 106

2 Answers2

0

For some reason I was having difficulty getting the global regular expression replace .replace(/ /g, '_') working within the curly braces. Instead, I opted for a solution from this SO answer.

<a ng-href="http://url.com/{{label.split(' ').join('_')}}">Click Me</a>

Here's the Codepen.

Keep in mind that ng-href is better than href because it will not throw a 404 before the curly braces are evaluated.

Community
  • 1
  • 1
Jack Guy
  • 8,346
  • 8
  • 55
  • 86
  • 1
    Angular does not allow regular expression creation within expressions; see the [docs](https://docs.angularjs.org/guide/expression). – David R Tribble Nov 24 '15 at 00:03
-1

Try this: JS Fiddle

var $link = document.getElementById('test'),
    $href = test.href;
    
test.addEventListener('mouseover', function(){
    $href = $href.replace(/%20/g, '_');
    console.log($href);
 this.href = $href;
});
<a id="test" href="https://url.com/a b c">Link Data</a>
Mi-Creativity
  • 9,554
  • 10
  • 38
  • 47