1

I need to get a part of URL with a variable which is not static. Using $("a[href*='.sometext']") which finds href value containing "sometext" string. But I need to pass a variable containing some string. Is there any way to pass a variable instead of hard coded string value?

  
  //comparing string "google": WORKING
  $("a[href*='.google']").css("background-color", "yellow");
  
  //passing variable with string wikipedia: NOT WORKING
  var name="wikipedia";
  $("a[href*=name]").css("background-color", "yellow");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://www.w3schools.com">w3schools.com</a><br>
<a href="http://www.google.com">Google.com</a><br>
<a href="http://www.wikipedia.org">wikipedia.org</a>
Kshri
  • 414
  • 3
  • 16

2 Answers2

2

below is updated snippet

  
  //comparing string "google": WORKING
  $("a[href*='.google']").css("background-color", "yellow");
  
  //passing variable with string wikipedia: NOT WORKING
  var name="wikipedia";
  $("a[href*="+name+"]").css("background-color", "yellow");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://www.w3schools.com">w3schools.com</a><br>
<a href="http://www.google.com">Google.com</a><br>
<a href="http://www.wikipedia.org">wikipedia.org</a>
AG_
  • 2,589
  • 3
  • 20
  • 32
1
var name="wikipedia";
$("a[href*="+name+"]").css("background-color", "yellow");

enter image description here

use this instead.

Atul Sharma
  • 9,397
  • 10
  • 38
  • 65