【问题标题】:Search and replace RegExp Affecting Parts of Words搜索和替换影响部分单词的 RegExp
【发布时间】:2013-12-17 19:05:18
【问题描述】:

所以我有一个脚本,它从我的列表中搜索一组单词,然后将它们转换为与单词具有相同类的链接,但问题是它也改变了单词的一部分。所以我的 once 变成 *on*ce 与我的脚本。 On、he、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

【问题讨论】:

    标签: javascript jquery regex search replace


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-08-07
      • 1970-01-01
      • 2021-08-26
      • 2011-09-25
      • 2011-09-13
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多