根據一條線:

s = "Test abc test test abc test test test abc test test abc";

这似乎只是在上面的行中删除ABC的第一次出现:

s = s.replace('abc', '');

如何替代所有事件?


当前回答

可以用常见的表达方式实现这一点,有几种可以帮助某人:

var word = "this,\\ .is*a*test,    '.and? / only /     'a \ test?";
var stri = "This      is    a test         and only a        test";

取代所有非阿尔法字符,

console.log(word.replace(/([^a-z])/g,' ').replace(/ +/g, ' '));
Result: [this is a test and only a test]

用一个空间替换多个连续空间,

console.log(stri.replace(/  +/g,' '));
Result: [This is a test and only a test]

取代所有 * 字符,

console.log(word.replace(/\*/g,''));
Result: [this,\ .isatest,    '.and? / only /     'a  test?]

取代问题标志(?)

console.log(word.replace(/\?/g,'#'));
Result: [this,\ .is*a*test,    '.and# / only /     'a  test#]

取代引用标志,

console.log(word.replace(/'/g,'#'));
Result: [this,\ .is*a*test,    #.and? / only /     #a  test?]

要取代所有“字符”,

console.log(word.replace(/,/g,''));
Result: [this\ .is*a*test    '.and? / only /     'a  test?]

替换一个特定的词,

console.log(word.replace(/test/g,''));
Result: [this,\ .is*a*,    '.and? / only /     'a  ?]

取代Backslash。

console.log(word.replace(/\\/g,''));
Result: [this, .is*a*test,    '.and? / only /     'a  test?]

以替代前滑,

console.log(word.replace(/\//g,''));
Result: [this,\ .is*a*test,    '.and?  only      'a  test?]

替换所有空间,

console.log(word.replace(/ /g,'#'));
Result: [this,\#.is*a*test,####'.and?#/#only#/#####'a##test?]

替换点,

console.log(word.replace(/\./g,'#'));
Result: [this,\ #is*a*test,    '#and? / only /     'a  test?]

其他回答

这个解决方案结合了一些以前的答案,并更好地符合建议的2020年8月标准解决方案,这个解决方案在2020年9月对我来说仍然可行,因为String.replaceAll不在我使用的Node.js二进制中。


RegExp.escape 是一个单独的问题处理,但它在这里很重要,因为官方提出的解决方案将自动逃脱基于链条的查找输入。


如果你需要准确的标准符合,对于一个应用程序,它是严格依赖于标准实施,那么我建议使用Babel或其他工具,你得到“正确的答案”每次而不是Stack Overflow。


代码:

if (!Object.prototype.hasOwnProperty.call(RegExp, 'escape')) {
  RegExp.escape = function(string) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping
    // https://github.com/benjamingr/RegExp.escape/issues/37
    return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  };
}

if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {
  String.prototype.replaceAll = function(find, replace) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
    // If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.
    // TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.
    // String parameters to 'find' do not require special handling.
    // Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace
    // Does not conform to "Specifying a function as a parameter" for replace
    return this.replace(
          Object.prototype.toString.call(find) == '[object RegExp]' ?
            find :
            new RegExp(RegExp.escape(find), 'g'),
          replace
        );
  }
}

编码,小型:

Object.prototype.hasOwnProperty.call(RegExp,"escape")||(RegExp.escape=function(e){return e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&")}),Object.prototype.hasOwnProperty.call(String,"replaceAll")||(String.prototype.replaceAll=function(e,t){return this.replace("[object RegExp]"==Object.prototype.toString.call(e)?e:new RegExp(RegExp.escape(e),"g"),t)});

例子:

console.log(
  't*.STVAL'
    .replaceAll(
      new RegExp(RegExp.escape('T*.ST'), 'ig'),
      'TEST'
    )
);

console.log(
  't*.STVAL'
    .replaceAll(
      't*.ST',
      'TEST'
    );
);

没有 RegExp.Escape 的代码:

if (!Object.prototype.hasOwnProperty.call(String, 'replaceAll')) {
  String.prototype.replaceAll = function(find, replace) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
    // If you pass a RegExp to 'find', you _MUST_ include 'g' as a flag.
    // TypeError: "replaceAll must be called with a global RegExp" not included, will silently cause significant errors. _MUST_ include 'g' as a flag for RegExp.
    // String parameters to 'find' do not require special handling.
    // Does not conform to "special replacement patterns" when "Specifying a string as a parameter" for replace
    // Does not conform to "Specifying a function as a parameter" for replace
    return this.replace(
          Object.prototype.toString.call(find) == '[object RegExp]' ?
            find :
            new RegExp(find.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'), 'g'),
          replace
        );
  }
}

代码没有 RegExp.Escape,小型:

Object.prototype.hasOwnProperty.call(String,"replaceAll")||(String.prototype.replaceAll=function(e,t){return this.replace("[object RegExp]"==Object.prototype.toString.call(e)?e:new RegExp(e.replace(/[.*+\-?^${}()|[\]\\]/g,"\\$&"),"g"),t)});

我已经阅读了这个问题和答案,但我找不到一个合适的解决方案,虽然答案是相当有用的,我决定创建自己的解决方案从切割。

例如,对于搜索结果,我需要用相同的案例取代它,如果我处理内部HTML,我可以轻松地损害HTML标签(例如,在href属性中出现 hr)。

因此,我写的功能,以突出搜索结果在一个表,在那里表数据细胞可能有链接在内部,以及其他HTML标签。

我決定為所有人提供相同的問題的解決方案. 當然,你可以用它不僅為表,但為任何元素。

/* Iterate over table data cells to insert a highlight tag */
function highlightSearchResults(textFilter) {
  textFilter = textFilter.toLowerCase().replace('<', '&lt;').replace('>', '&gt;');
  let tds;
  tb = document.getElementById('sometable'); //root element where to search
  if (tb) {
    tds = tb.getElementsByTagName("td"); //sub-elements where to make replacements
  }
  if (textFilter && tds) {
    for (td of tds) {
      //specify your span class or whatever you need before and after
      td.innerHTML = insertCaseInsensitive(td.innerHTML, textFilter, '<span class="highlight">', '</span>');
    }
  }
}

/* Insert a highlight tag */
function insertCaseInsensitive(srcStr, lowerCaseFilter, before, after) {
  let lowStr = srcStr.toLowerCase();
  let flen = lowerCaseFilter.length;
  let i = -1;
  while ((i = lowStr.indexOf(lowerCaseFilter, i + 1)) != -1) {
    if (insideTag(i, srcStr)) continue;
    srcStr = srcStr.slice(0, i) + before + srcStr.slice(i, i+flen) + after + srcStr.slice(i+flen);
    lowStr = srcStr.toLowerCase();
    i += before.length + after.length;
  }
  return srcStr;
}

/* Check if an ocurrence is inside any tag by index */
function insideTag(si, s) {
  let ahead = false;
  let back = false;
  for (let i = si; i < s.length; i++) {
    if (s[i] == "<") {
      break;
    }
    if (s[i] == ">") {
      ahead = true;
      break;
    }
  }
  for (let i = si; i >= 0; i--) {
    if (s[i] == ">") {
      break;
    }
    if (s[i] == "<") {
      back = true;
      break;
    }
  }
  return (ahead && back);
}

方法1

尝试执行一个常见的表达式:

“测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试

方法2

与ABC分开并加入空空间。

“测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试

首頁 〉外文書 〉文學 〉文學 〉In string first element search and replace

此分類上一篇: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員:

在线全球搜索和替换

var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}' var j = str.replace(/\"\][g,'[').replace(/\]\"/g,']'); console.log(j,'//global search and replace')

把它推到发生的数字达到0,如下:

function replaceAll(find, replace, str) {
    while (str.indexOf(find) > -1) {
        str = str.replace(find, replace);
    }
    return str;
}