根據一條線:

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

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

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

如何替代所有事件?


当前回答

要取代所有类型的字符,请尝试此代码:

假设我们需要发送“和 \ 在我的行中,然后我们将转换“到“和 \ 到“。

因此,这种方法将解决这个问题。

String.prototype.replaceAll = function (find, replace) {
     var str = this;
     return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
 };

var message = $('#message').val();
message = message.replaceAll('\\', '\\\\'); /*it will replace \ to \\ */
message = message.replaceAll('"', '\\"');   /*it will replace " to \\"*/

我使用Ajax,我需要在JSON格式发送参数,然后我的方法看起来如下:

 function sendMessage(source, messageID, toProfileID, userProfileID) {

     if (validateTextBox()) {
         var message = $('#message').val();
         message = message.replaceAll('\\', '\\\\');
         message = message.replaceAll('"', '\\"');
         $.ajax({
             type: "POST",
             async: "false",
             contentType: "application/json; charset=utf-8",
             url: "services/WebService1.asmx/SendMessage",
             data: '{"source":"' + source + '","messageID":"' + messageID + '","toProfileID":"' + toProfileID + '","userProfileID":"' + userProfileID + '","message":"' + message + '"}',
             dataType: "json",
             success: function (data) {
                 loadMessageAfterSend(toProfileID, userProfileID);
                 $("#<%=PanelMessageDelete.ClientID%>").hide();
                 $("#message").val("");
                 $("#delMessageContainer").show();
                 $("#msgPanel").show();
             },
             error: function (result) {
                 alert("message sending failed");
             }
         });
     }
     else {
         alert("Please type message in message box.");
         $("#message").focus();

     }
 }

 String.prototype.replaceAll = function (find, replace) {
     var str = this;
     return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
 };

其他回答

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

例如,对于搜索结果,我需要用相同的案例取代它,如果我处理内部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);
}

以下功能为我工作:

String.prototype.replaceAllOccurence = function(str1, str2, ignore)
{
    return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} ;

现在,请称这些功能如下:

"you could be a Project Manager someday, if you work like this.".replaceAllOccurence ("you", "I");

简单地复制并将此代码插入您的浏览器控制台进行测试。

2020年8月

不再有常见的表达式

const str = “测试 abc 测试 abc 测试 abc 测试 abc”; const modifiedStr = str.replaceAll('abc', ''); console.log(modifiedStr);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/参考/Global_Objects/String/replaceAll

var str = "ff ff f f a de def";
str = str.replace(/f/g,'');
alert(str);

HTTP://jsfiddle.net/ANHR9/

String.prototype.replace 所有()

如果你不想处理替代() + RegExp。

但是,如果浏览器在2020年之前?

我推荐的替代All polyfill的选项:

替代All polyfill (与全球旗帜错误) (更多原则版)

if (!String.prototype.replaceAll) { // Check if the native function not exist
    Object.defineProperty(String.prototype, 'replaceAll', { // Define replaceAll as a prototype for (Mother/Any) String
        configurable: true, writable: true, enumerable: false, // Editable & non-enumerable property (As it should be)
        value: function(search, replace) { // Set the function by closest input names (For good info in consoles)
            return this.replace( // Using native String.prototype.replace()
                Object.prototype.toString.call(search) === '[object RegExp]' // IsRegExp?
                    ? search.global // Is the RegEx global?
                        ? search // So pass it
                        : function(){throw new TypeError('replaceAll called with a non-global RegExp argument')}() // If not throw an error
                    : RegExp(String(search).replace(/[.^$*+?()[{|\\]/g, "\\$&"), "g"), // Replace all reserved characters with '\' then make a global 'g' RegExp
                replace); // passing second argument
        }
    });
}

替代All polyfill (With handling global-flag missing by itself) (我的第一个偏好) - 为什么?

if (!String.prototype.replaceAll) { // Check if the native function not exist
    Object.defineProperty(String.prototype, 'replaceAll', { // Define replaceAll as a prototype for (Mother/Any) String
        configurable: true, writable: true, enumerable: false, // Editable & non-enumerable property (As it should be)
        value: function(search, replace) { // Set the function by closest input names (For good info in consoles)
            return this.replace( // Using native String.prototype.replace()
                Object.prototype.toString.call(search) === '[object RegExp]' // IsRegExp?
                    ? search.global // Is the RegEx global?
                        ? search // So pass it
                        : RegExp(search.source, /\/([a-z]*)$/.exec(search.toString())[1] + 'g') // If not, make a global clone from the RegEx
                    : RegExp(String(search).replace(/[.^$*+?()[{|\\]/g, "\\$&"), "g"), // Replace all reserved characters with '\' then make a global 'g' RegExp
                replace); // passing second argument
        }
    });
}

小型(我的第一个偏好):

if(!String.prototype.replaceAll){Object.defineProperty(String.prototype,'replaceAll',{configurable:!0,writable:!0,enumerable:!1,value:function(search,replace){return this.replace(Object.prototype.toString.call(search)==='[object RegExp]'?search.global?search:RegExp(search.source,/\/([a-z]*)$/.exec(search.toString())[1]+'g'):RegExp(String(search).replace(/[.^$*+?()[{|\\]/g,"\\$&"),"g"),replace)}})}


其他方法的聚合物分配

if (!String.prototype.replaceAll) {
    String.prototype.replaceAll = function(search, replace) { // <-- Naive method for assignment
        // ... (Polyfill code Here)
    }
}

for (var k in 'hi') console.log(k);
// 0
// 1
// replaceAll  <-- ?

非常可靠,但重

事实上,我提出的选项有点乐观,正如我们信任环境(浏览器和Node.js),它肯定是2012年至2021年左右。

此分類上一篇: HTTPS://polyfill.io

特别是替代:

<script src="https://polyfill.io/v3/polyfill.min.js?features=String.prototype.replaceAll"></script>