搜索并替换影响词语部分的RegExp

时间:2013-12-02 06:26:47

标签: javascript jquery regex search replace

所以我有一个脚本,从我的列表中搜索一系列单词,然后将它们转换为与单词相同的类的链接,但问题是它也在改变单词的部分。所以我的曾经使用我的脚本成为* on * ce。在,他,a,an等都搞砸了许多话。我怎么做才影响整个单词?

var words = ['able','about','after','all','along','an','and','arrived','as','asked','at','ate','attacked','baby','back','bad','baddies','be','became','before','Behind','being','big','biting','boat','borrowed','boy','boys','burst','by','came','care','causing','children','chores','collect','come','common','continued','couple','cut','dango','day','decided','demon','demons','did','did','difficult','do','dog','doing','eat','energy','enjoy','even','ever','everyone','evil','farewell','fight','find','firewood','floating','for','found','friends','from','gate','gave','gift','give','go','God','gold','got','green','grew','guessed','guys','had','happily','have','he','He','heard','help','her','him','his','home','houses','However','husband','in','including','into','is','island','it','Japan','Japanese','joined','journey','keep','lady','large','laundry','left','lived','looked','lot','lots','man','mean','met','momo','Momotaro','monkey','more','mountain','much','name','no','not','of','off','ogres','old','on','Once','One','open','out','own','pain','path','peach','pecking','people','pheasant','power','problems','quest','quickly','ran','real','red','returned','river','said','sailed','saw','screamed','see','seen','sell','set','She','shock','smashed','so','some','soon','special','spotted','stayed','stolen','stop','story','strong','surprised','take','Taro','tasty','terrible','terrorising','that','The','their','them','there','they','things','this','though','thought','through','time','to','too','took','up','upon','used','Using','village','walked','was','way','were','When','where','which','while','with','woman','work','would','you'],

    reg = new RegExp('(' + words.join('|') + ')', 'g');

    jQuery('.thestory').html(function (_, curHtml) {
        return curHtml.replace(reg, "<a href='#' class='$1'>$1</a>");
    });

感谢您的帮助m(-_-)m

1 个答案:

答案 0 :(得分:4)

\b表示单词边界,所以:

var reg = new RegExp('\\b(' + words.join('|') + ')\\b', 'g');