469,278 Members | 2,391 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,278 developers. It's quick & easy.

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

Dasty
101 Expert 100+
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 ...
Feb 25 '08 #1
4 1155
acoder
16,027 Expert Mod 8TB
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>.
Feb 25 '08 #2
gits
5,390 Expert Mod 4TB
i just came out the following way:

Expand|Select|Wrap|Line Numbers
  1. var s  = 'This is my site http://www.try.org/see.html and I would like to replace it';
  2. var ma = s.match(/(http[:/\w.]+)/)[1];
  3. var li = '<a href="' + ma + '">' + ma + '</a>';
  4.  
  5. var new_text = s.replace(s1[1], li);
  6.  
  7. alert(new_text);
kind regards
Feb 25 '08 #3
Dasty
101 Expert 100+
Thanks. I really love you guys.

I ended up with this:

Expand|Select|Wrap|Line Numbers
  1. mystr.replace(/((https?|ftp):\/\/[^\s]+)/g, '<a href="$1">$1</a>');
Which is enough for my needs.
Feb 25 '08 #4
acoder
16,027 Expert Mod 8TB
No problem. Glad it helped.
Feb 25 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

14 posts views Thread by php newbie | last post: by
5 posts views Thread by Mahesha | last post: by
7 posts views Thread by Billa | last post: by
1 post views Thread by Matthias S. | last post: by
1 post views Thread by NvrBst | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.