3

I want to search the string in anchor tag, When I simply search the "Happy" without space it works fine however when I search it with some space like "Happy " it does not work.

Below is the code sample:

<html>
<body>

 <a style="color:#555555" href="Happy coding!!">test</a>
<br/>

<script type="text/javascript">

var hrefTags = document.getElementsByTagName("a");
var bDayId = ""; 
var stringToSearch = "Happy coding!!";
    for(var hrefIndex=0; hrefIndex < hrefTags.length; hrefIndex ++){
bDayId = hrefTags.item(hrefIndex).href.toString(); 
document.write(bDayId+"<br/>");
document.write( bDayId.indexOf("Happy "));  
     }  

</script>

</body>
</html>

4 Answers 4

2

its because href being a URL gets URL encoded , space becomes '%20' . Href with a space is an invalid href, hence use another attribute if you want to store some information in href attribute, or if you want to read and string compare href attribute with spaces, compare after proper url decoding. http://jsfiddle.net/Sddv6/1/

var hrefTags = document.getElementsByTagName("a");
var bDayId = ""; 
var stringToSearch = "Happy coding!!";
for(var hrefIndex=0; hrefIndex < hrefTags.length; hrefIndex ++){
  bDayId = decodeURIComponent(hrefTags.item(hrefIndex).href);      
  document.write(bDayId);    
  document.write(bDayId+"<br/>");
  document.write( bDayId.indexOf("Happy "));  
}  
Sign up to request clarification or add additional context in comments.

Comments

0

Use regular expression for matching the string look at the following URL will help: http://www.tizag.com/javascriptT/javascript-string-replace.php

Comments

0

The space will be encoded as "%20" while retrieving from the link href attribute. Try something below:

bDayId = decodeURIComponent(hrefTags.item(hrefIndex).href.toString());

Comments

0

When I do that in Firefox, the string I get from toString() is:

file:///home/pax/Happy%20coding!!

If that's what you're seeing then of course you won't be able to find "Happy " in there. When I change the search statement to:

document.write( bDayId.indexOf("Happy%20"));

then it works fine.

Perhaps you may want to think about url-encoding the search string similar to the way your browser does it in toString():

document.write( bDayId.indexOf(encodeURIComponent("Happy ")));

This is, of course, assuming I'm right about the encoding. You didn't provide the actual output from your HTML so it's a little difficult to tell.

It would be worthwhile posting that as an edit to your question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.