Solved

Placeholder string variable in javascript?

Posted on 2006-12-01
21
478 Views
Last Modified: 2008-02-01
I am trying to search a string that shows up on each page of a website to grab the current user's username.  This string of text:

Welcome <a href="/display/~testuser">

and

<a href="/users/viewuserprofile.action?username=testuser">

Are on each page.  I would like to be able to grab the 8 characters after the end of   ~  in the first string or   = in the second.  I have written some @Left, @Right functions in javascript etc but dont know how to tell it to "grab the next 8 characters at the end of this string..."

(all our usernames are 8 characters long.)

I would like to be able to say:

@middle(<a href="/users/viewuserprofile.action?username=########">) or something along those lines...

Thanks!  
0
Comment
Question by:wildbrookmedia
  • 13
  • 5
  • 3
21 Comments
 
LVL 54

Expert Comment

by:b0lsc0tt
Comment Utility
wildbrookmedia,

Is the script going to be on the page itself or is this a different website?  I don't think Javascript is what you want, especially if you are searching multiple pages.  There are programs that will "scrape" the pages of a website and then you could search the results.  If not with that same program then another.  A server language like PHP may be another option.  It has a component called CURL which I believe would allow you to do this.

The main point is javascript is going to work unless I misunderstood what you want to do.  Please provide more details if I did misunderstand or if you have questions.  Let me know if you have any questions or need more information.

b0lsc0tt
0
 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
The script will be on the page itself, in the script block at the top of each page.  What I think I need to do is:

1.  Use the DOM to get the link object on the page.
2.  Cycle through the link objects on the page and snag the href attribute of the link that equals (2nd example) this one:  /users/viewuserprofile.action?username
3.  Store that link in a variable
4.  Grab the rightmost characters after the ? symbol and store that in a username javascript variable...

I may not have used the right terms, but I believe that is what I am after...  Not sure if that clears it up...
0
 
LVL 54

Expert Comment

by:b0lsc0tt
Comment Utility
That does help and we should be able to use javascript.  Is the page (the URL) unique?  In other words we could get all of the html of the page and use a regular expression to find the URL with the page and querystring.  I haven't tried this before but think I can make a function for you.  You would need to use the onload event in the body tag to call the function or have some button to fire it.  The other option would be script at the very end of the html, right before the body closing tag.  Otherwise the page isn't done so the function would have a problem.

Please confirm this stuff/answer questions and then I can give you a function or script to try.

bol
0
 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
Yes each page has a different url...
0
 
LVL 54

Expert Comment

by:b0lsc0tt
Comment Utility
Does the anchor that contain the URL have an id?  Is it the same on each page, even if the url is different?  If that is the case then it will be easy.

bol
0
 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
The ending section of the url is different for each page of the website.  A page about zebras:
http://mydomain.com/display/BP/about+zebras

tigers:
http://mydomain.com/display/BP/about+tigers

But why does the url matter when the function is searching for a specific string in the html of the page?
0
 
LVL 51

Accepted Solution

by:
ahoffmann earned 500 total points
Comment Utility
for (var i in document.links) {
  var path = document.links[i].pathname;
  var search = document.links[i].search;
  if (path.match(/[^/\?#]*/)) {
      // extract your name here as you like
  }
  if (search) {
      // extract your name here as you like
  }
}
0
 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
//i cant get the search to equal the href attribute...  Although it never will because the href attribute on the page has a username at the end of it...

function getLinks()
{
var links = document.links;
var myLink = "";
for(var i; i < links.length; i++)
      {
      if (document.links[i].href == "/users/viewuserprofile.action?username=")
            {
            mylink = document.links[i].href;
            alert(myLink);
            }
      //else
            //{
            //myResult = param1;
            //}
      }

}

</script>
0
 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
Sorry, ahoffman, didnt see your post as i didnt refresh the page before i posted...  :$  I will give that a try but am not sure how to use it as I am very unfamiliar with regex...
0
 
LVL 51

Expert Comment

by:ahoffmann
Comment Utility
if you're not used to regex, you also may use indexOf(), or lastIndexOf(), or split(), but that needs more coding ...
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
I guess I dont understand where I am to put what I am searching for into your code you provided.  
0
 
LVL 51

Expert Comment

by:ahoffmann
Comment Utility
ok, with my suggestion to get 2 variables which probably contain what you want
to extract the user name from the path you can do:

  var dirs=path.split('/');
  for (var k in dirs) {
     if (dirs[k].match(/^~/)) { alert('heureca:'+dirs[k]); break; }
  }

With path.match() you may do it in a single statement, ....
0
 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
Man I just cant get the regex to go... Would you be able to help with what I almost have working?  (realizing that the regex is probably more efficient and I will come back to it when this is answered)  not in this question though...  ;)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>userNameTest</TITLE>
</HEAD>

<script language="JavaScript" type="text/javascript">
function getLinks()
{
var len = document.links.length;
var myLink = "";
for (var i = 0; i < len; i++)
      {
      //searching for the link that has this text in it
      if (document.links[i].href.indexOf == "/users/viewuserprofile.action?username=")
            {
            //if the link exists, it is the link we want
            myLink = document.links[i].href;
            //simply alerting for now but will do some parsing after I get the alert to fire and know i am finding the link I want
            alert(myLink);
            }
      }
}
</script>

<BODY onLoad="getLinks()">
                                                   
    <span class="smalltext">
    Welcome <a href="/display/~testuser">Test User</a> |

            <a href="/users/viewuserhistory.action" onClick="window.open(this.href,'user_history', 'width=620, height=200, resizable'); return false;" title="View History">History</a> |
           
            <a href="/users/viewuserprofile.action?username=testuser">Preferences</a> |

            <a href="/admin/console.action">Administration</a> |
            
            <a href="/logout.action" id="logout">Log Out</a>

     </span>

</BODY>
</HTML>
0
 
LVL 51

Expert Comment

by:ahoffmann
Comment Utility
>      if (document.links[i].href.indexOf == "/users/viewuserprofile.action?username=")
why do you use the href property?
In you description you tell us that the username is either in the path or the search part of the URL, so use just them.

      if (document.links[i].pathname == "/users/viewuserprofile.action") {
              var user= document.links[i].search.split('=')[1];
              alert(document.links[i].href);
      }

NOTE, that this is a lazy aproach and may fail if you have a more complex URL
0
 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
I was going to get the href property because i was then going to parse it a bit further to grab the username...  The url should be the same on each page as i havent found one yet in the application where it is different.  I will give your code a go when I get back into work tomorrow.
0
 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
I replaced my code with yours in the header and cant even get that alert to fire...  I am using IE6 if it makes any difference.
0
 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
Almost have it, I am finding the username but when I put the code inside the if block, it isnt firing as I must have that written wrong somehow...
(I have an atRight function that i am using but dont want to post that code as this thread is long enough!)  :)

function getLinks()
{
var len = document.links.length;
var myLink = "";
var username = "";
var searchChar = "=";
for (var i = 0; i < len; i++)
      {
      var myLink = document.links[i].href;
      myLink.toString();
      //searching for the link that has this text in it
      if (myLink.indexOf("/users/viewuserprofile.action?username=") > 0) //the index is usually 10 or more but I am not getting inside this code block
            {
            username = atRight(myLink, searchChar);
            //alert("username = " + username);
            }
            else {
            //it isnt the link we want
            }
      }
}
0
 
LVL 51

Expert Comment

by:ahoffmann
Comment Utility
>       if (myLink.indexOf("/users/viewuserprofile.action?username=") > 0) //the index is usually 10 or more but I am not getting inside this code block

what do you expect does myLink.indexOf() return? PLease post a working example of mylink and the result.
0
 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
what do you expect does myLink.indexOf() return?
in my test it is returning 10...

This function will alert on the indexOf mylink and also alert what the username is using the atRight function I wrote.  (i pass it the string to search and the = character, it gives me everything to the right of that.)

copy all this code and paste in a new html doc...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>userNameTest</TITLE>
</HEAD>

<script language="JavaScript" type="text/javascript">

function atRight(param1,param2)
{
var pos = -1;
var myResult = "";
var startIndex = "";
var lenParam1 = param1.length;
if ( isNaN(param2) )                        //param2 is not a number
  {
  pos = param1.indexOf(param2);
  if ( pos > -1 )
    {
    myResult = param1.substr((pos+1),lenParam1);
    }
  else
    {
    myResult = "";
    }
  }
else                                                            //param2 is a number
  {
  pos = param2;
  startIndex = lenParam1 - pos;
  if (pos > 0)
    {
    myResult = param1.substr(startIndex, pos);
    }
  else if (pos == 0)                                    //if they put in a zero, dont give them back anything...
    {
    myResult = "";
    }
  else                                                            //if param2 is negative give them back the whole string as that is what Notes does
    {
    myResult = param1;
    }
  }
  return myResult;
}

function getLinks()
{
var len = document.links.length;
var myLink = "";
var username = "";
var searchChar = "=";
for (var i = 0; i < len; i++)
      {
      var myLink = document.links[i].href;
      myLink.toString();
      myLink.indexOf("/users/viewuserprofile.action?username=");
      alert(myLink.indexOf("/users/viewuserprofile.action?username="));
      username = atRight(myLink, searchChar);
      alert("username = " + username);
      }
/*
for (var i = 0; i < len; i++)
      {
      var myLink = document.links[i].href;
      myLink.toString();
      //searching for the link that has this text in it
      //ALMOST WORKING - Cant get this if test to fire...
      if (myLink.indexOf("/users/viewuserprofile.action?username=") > 0) //the index is usually 10 or more but I am not getting inside this code block
            {
            username = atRight(myLink, searchChar);
            //alert("username = " + username);
            }
            else {
            //it isnt the link we want
            }
      }
      */
}
</script>

<BODY onLoad="getLinks()">
                                                   
    <span class="smalltext">
    Welcome <a href="/display/~testuser">Test User</a> |
            </br>
            </br>
            <a href="/users/viewuserprofile.action?username=testuser">Preferences</a> |

     </span>

</BODY>
</HTML>
0
 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
interesting, it appears that the / character was causing issues in the if statement of the indexOf clause.  if you replace the for loop in the above code, the if statement works:

for (var i = 0; i < len; i++)
      {
      var myLink = document.links[i].href;
      myLink.toString();
        //note the string is missing /users/ which is acceptable in this case
      if (myLink.indexOf("viewuserprofile.action?username=") > 0)
            {
            username = atRight(myLink, searchChar);
            alert("username = " + username);
            }
            else {
            //it isnt the link we want
            }
      }
0
 
LVL 8

Author Comment

by:wildbrookmedia
Comment Utility
Recommendations on how to close out this question and split points?
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

I've been trying to accomplish this for a while and it just struck me yesterday how to accomplish this task. I have done searches all over the internet looking for ways to email pages from my applications and finally I have done it!!! Every single s…
Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now