Home > OS >  remove "?" from all anchor text
remove "?" from all anchor text

Time:03-29

i am trying to remove the query string "?" from all anchor text with javascript

for example, there are many URLs like this

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

i just want to remove ? from all anchor text. 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;

CodePudding user response:

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

  • Related