简体   繁体   中英

JavaScript RegExp replace text

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.

用括号将您的单词regexp括起来,使其成为捕获组,替换字符串将其识别为$ 1:

/#([\w\dğüşçöı]+)/gi

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM