0

I have a data source that I can not alter, the data source contains a hyperlink with an Id in it that I can use to retrieve data that I need. I created a method to convert the hyperlink to call a javascript function and pass the scrubbed id from the hyperlink, however I am not getting the correct results. In its current state everything is working except the insertion of the id var into the ClickIt method. For this example the value of id is djb137, and when I click on the new hyperlink the error returned is 'djb137 is undefined. Am I overlooking something on passing a paramater to a javascript function?

private string ScrubHref(string statementHtml)
    {
        string pattern = "href.*?\"(?<href>.*?)\"";

        return Regex.Replace(statementHtml, pattern, delegate(Match match)
        {
            string v = match.ToString();

            string id = Regex.Match(v, "\"([^\"]*?)\"").Groups[1].Value;

            string returnValue = "href=\"#\"" + "onclick=\"return ClickIt("+id+");\"";

            return returnValue;
        });
    }

Intrestingly If I change the retrunValue string to this

return v + "onclick=\"return ClickIt(this.href);\"";

Then my javascript function gets the whole href passed to it without issue.But I just need the Id not the whole href.

Siegeon
  • 610
  • 3
  • 15
  • 33
  • 1
    Parsing HTML with regular expressions is a very bad thing and could have some negative consequences such as those outlined here: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – Darin Dimitrov Nov 29 '11 at 16:55
  • Love that answer in that link but only for its derangement. In general, there's no problem with parsing HTML with regular expressions - as long as you actually understand regular expressions and aren't simply copying them off Google. – Dracorat Nov 29 '11 at 17:05
  • Since I all I needed to do was capture the specific id in the href I figured a quick regex would not not be a problem here. – Siegeon Nov 30 '11 at 14:42

2 Answers2

1

You need to quote your id as you pass it in to your function call.

The line

string returnValue = "href=\"#\"" + "onclick=\"return ClickIt("+id+");\"";

Should be

string returnValue = "href=\"#\"" + "onclick=\"return ClickIt('"+id+"');\"";

What's happening is it thinks djb137 is a variable name, think how the method calls would look if you weren't constructing them in this way. What's the difference between the following

return ClickIt(djb137); // looks like a variable identifier

return ClickIt('djb137'); // passing a string to the function call
Greg B
  • 14,597
  • 18
  • 87
  • 141
1

Change this line:

string returnValue = "href=\"#\"" + "onclick=\"return ClickIt("+id+");\"";

to

string returnValue = "href=\"#\"" + "onclick=\"return ClickIt('"+id+"');\"";

Note the additional quotes in it.

Dracorat
  • 1,184
  • 7
  • 12