1

I am trying to remove the ? character from all anchor href values with Javascript. For example, there are many URLs like this:

<a href="https://example.com/something/?">my anchor</a>

I tried this but getting the error index of is not a function

var url = jQuery("a");
var a = url.indexOf("?");
var b =  url.substring(a);
var c = url.replace(b,"");
url = c;
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Uxair
  • 37
  • 4
  • 2
    `url` is a jquery object representing an anchor element. Use `url[0].href` instead, or `url.attr('href', ...)` – evolutionxbox Mar 29 '22 at 14:58
  • jQuery("a") return an element not a String, element doesn't have indexOf method that's why you get this error. – Saver Mar 29 '22 at 15:00

1 Answers1

0

To achieve this you can provide a function to prop() which runs against all elements in the collection. In the function you can accept the current href value as an argument then use replace() to remove the ? characters:

$('a').prop('href', (i, h) => h.replace(/\?/g, ''));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://example.com/something/?">my anchor 1</a>
<a href="https://example.com/somethingelse/?">my anchor 2</a>
<a href="https://example.com/?something">my anchor 2</a>

Note that this will replace all instances of ? from anywhere in the href value. If you only want to remove it from the end of the string change the regex to /\?$/g

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Why `prop` over `attr`? – evolutionxbox Mar 29 '22 at 15:00
  • @evolutionxbox for me, performance mainly, but this excellent answer covers the differences: https://stackoverflow.com/a/5876747/519413 – Rory McCrossan Mar 29 '22 at 15:33
  • I had an SO answer dowvoted because I (correctly) used .attr - downvoter said their senior dev had told them "just always use .prop" *facepalm* – freedomn-m Mar 29 '22 at 15:45
  • I would say generally use `prop()` over `attr()`, but `attr()` still has its place - for example `prop('href')` wil return the root URL, whereas `attr('href')` will return just the relative path in the HTML. In the case above it doesn't make a difference as the OP was using the full URL already. – Rory McCrossan Mar 29 '22 at 15:47