【问题标题】:replace the [x] match using jquery使用 jquery 替换 [x] 匹配项
【发布时间】:2016-06-19 22:20:56
【问题描述】:

我有一个字符串:

"josh marie anne josh anne marie chloe josh anne ..."

如果我找到了 josh,我想替换为 JJJ。所以我有一个这样的字符串替换:

var p = 'josh';
var username = 'JJJ';

$("#comment").val($("#comment").val().replace(p, username));

问题是,我不想替换字符串中的第一个 josh...我想选择一个替换(#comment 中的第二个 josh 或第三个中的第一个 josh ...)

任何想法如何选择一个替换?

html

<textarea id=comment>josh marie anne josh anne marie chloe josh anne josh marie anne josh anne marie chloe josh anne</textarea>

https://jsfiddle.net/tbjswpLb/

【问题讨论】:

  • @rory OP 不想替换所有出现的地方。而是他想要的发生。假设如果它匹配 7 个单词,他必须从中选择任何一个匹配项并替换。
  • @RajaprabhuAravindasamy 谢谢你的朋友!

标签: jquery


【解决方案1】:

答案来自:jquery-find-and-replace-second-one

fiddle

更新的脚本:

var p = 'josh';
var username = 'JJJ';

var out = replaceMatch( $("#comment").val(), p, username, 2)

$("#comment").val(out);

function replaceMatch(originalString, searchFor , replaceWith, matchNumber)
{
  var match = 0;
  return originalString.replace(searchFor, function(found){
    match++;
    return (match===matchNumber)?replaceWith:found;
  },'g');
}

【讨论】:

    【解决方案2】:

    你可以这样重写你的逻辑来实现你想要的,

    var p = 'josh',username = 'JJJ',cnt = 0,replaceAt = 3;
    var regEx = new RegExp(p,"g")
    
    $("#comment").val($("#comment").val().replace(regEx,function(matchedString){
      return (++cnt == replaceAt) ? username : matchedString;
    }));
    

    使用replacecallBack函数匹配出现序列。

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      相关资源
      最近更新 更多