Search code examples
javascriptregexhref

Using Javascript Regex to get part of Href During Mouseover


I has this Html Code below

<div class="first-div">
    <ul>
        <li><a href="http://localhost/wordpress/2014/04/18/post-format-audio-2/#php">PHP</a></li>
        <li><a href="http://localhost/wordpress/2014/04/18/post-format-audio-2/#css">CSS</a></li>
        <li><a href="http://localhost/wordpress/2014/04/18/post-format-audio-2/#html">HTML</a></li>
    </ul>
</div>

<div class="second-div"></div>

i want when mouseover on PHP,CSS and HTML Link:

  1. Create The Javascript REGEX to get only (php,css,html) without # sign from href in first-div.
  2. then add (php,css,html) as ID to second-div.

Solution

  • You don't need a regex, the part after the # is a hash, and is available directly.

    $('a').on('mouseover', function(e) {
        e.preventDefault();
    
        $('.second-div').prop('id', this.hash.substr(1));
    });
    

    Not sure why you would ever set the ID dynamically, but whatever floats your goat !

    enter image description here