Jitendra Zaa
Jitendra Zaa

Reputation: 212

javascript function indexOf() not working in chrome with white space in string

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>

Upvotes: 3

Views: 6609

Answers (4)

paxdiablo
paxdiablo

Reputation: 881263

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.

Upvotes: 0

Chris
Chris

Reputation: 613

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

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

Upvotes: 0

DhruvPathak
DhruvPathak

Reputation: 43235

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 "));  
}  

Upvotes: 2

Ahmy
Ahmy

Reputation: 5480

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

Upvotes: 0

Related Questions