0

I want to wrap around a #hashtag with <a href=''></a> in a sentence. I created a regular expression var exp = /#[\w\dğüşçöı]+/gi.

That expression works perfectly fine but I can't replace a #hey dude! string with

<a href='hashtag/hey'>#hey</a> dude!

jsFiddle example.

2
  • 1
    So what's the question? Commented Oct 20, 2014 at 14:16
  • Convert #hey into <a href='hashtag/hey>#hey</a> form. Commented Oct 20, 2014 at 14:17

2 Answers 2

1

Surround your word regexp with brackets to make it a capture group that will be recognized by the replacement string as $1:

/#([\w\dğüşçöı]+)/gi
Sign up to request clarification or add additional context in comments.

7 Comments

Note that this will throw away the # - you'll need to re-include it in the replace text
Thank you. I'll kindly accept your answer in 10 minutes.
not now you've included it in the capture group it isn't, but it has been added to your /hashtag/#url though, which isn't what you intended
@JamesThorpe Is it safe to use '#' in URL?
depends what the intention of the url is...! I'd guess in your case probably not. What this will do is load whatever page is at /hashtag/ and then try to navigate to the #hash anchor on that page, rather than just navigating to the page served by /hashtag/hash
|
0

I found a solution in a similar PHP-Question (https://stackoverflow.com/a/4277114/4161041):

var raw = "Hello #world! #hey dude!";
var pattern = /#(\w*[a-zA-Z_ğüşçöı]+\w*)/ig;
var replacement = "<a href=\"hashtag/$1\">#$1</a>";
var parsed = raw.replace(pattern, replacement);

http://jsfiddle.net/j3pttLnz/

I hope this helps.

3 Comments

That's PHP. I'm trying to reduce server's load with doing it with JavaScript. But thank your for finding it. I'll use it for pre-loaded content with PHP.
Nope, it's JavaScript. I just used the expression from the PHP-Topic. Try my example by clicking jsfiddle-link ;-)
Oh, selective perception. I thought that's a PHP code when I read PHP-Question :D Didn't read rest of the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.