Search code examples
jqueryformsanchor

jQuery val() with removing URL path


I have a simple script to set a value for an input field.

jQuery(document).on('click','#getit', function() {
  jQuery("#getitout").val(api.get_video_link());
});
  

The api.get_video_link() returns this URL with an anchor:

domain.com/post_type/post_name/#anchor

How can I remove the url path and set only the anchor as value for my input field?

The input field value should be #anchor


Solution

  • Simply use regex:

    jQuery(document).on('click','#getit', function() {
      let url = api.get_video_link();
      jQuery("#getitout").val(url.match(/.*?(\#.+$)/)[1]);
    });