Is it possible to write reg.expression for such a replace?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dasty
    Recognized Expert New Member
    • Nov 2007
    • 101

    Is it possible to write reg.expression for such a replace?

    My problem:

    My users will write some text into <textarea> area. All I want to do with javascript is to take that textarea.value and replace all url links there with regular <a href> and then put whole text (with replaced urls) into another div.

    Let's show it on example:

    User will write sentence:

    "This is my site http://www.try.org/see.html and I would like to replace it"

    and I want my javascript to replace all urls this way:

    "This is my site <A HREF="http://www.try.org/see.html">http://www.try.org/see.html</A> and I would like to raplce it"

    Is it possible to make such a replacement with regular expression? (Yes, I can solve such a problem just by splitting string by words and test each word if it is not link) But I really want to know if it is doable by just .replace() function.

    Thanks ...
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    I assume you know how to match a URL. Use parentheses around the reg. exp. for capturing. Then use $1 to refer to the captured match, e.g. the replacement could be <a href="$1">$1</a>.

    Comment

    • gits
      Recognized Expert Moderator Expert
      • May 2007
      • 5390

      #3
      i just came out the following way:

      [CODE=javascript]var s = 'This is my site http://www.try.org/see.html and I would like to replace it';
      var ma = s.match(/(http[:/\w.]+)/)[1];
      var li = '<a href="' + ma + '">' + ma + '</a>';

      var new_text = s.replace(s1[1], li);

      alert(new_text) ;[/CODE]
      kind regards

      Comment

      • Dasty
        Recognized Expert New Member
        • Nov 2007
        • 101

        #4
        Thanks. I really love you guys.

        I ended up with this:

        [CODE=javascript]mystr.replace(/((https?|ftp):\/\/[^\s]+)/g, '<a href="$1">$1</a>');[/CODE]

        Which is enough for my needs.

        Comment

        • acoder
          Recognized Expert MVP
          • Nov 2006
          • 16032

          #5
          No problem. Glad it helped.

          Comment

          Working...