根據一條線:
s = "Test abc test test abc test test test abc test test abc";
这似乎只是在上面的行中删除ABC的第一次出现:
s = s.replace('abc', '');
如何替代所有事件?
根據一條線:
s = "Test abc test test abc test test test abc test test abc";
这似乎只是在上面的行中删除ABC的第一次出现:
s = s.replace('abc', '');
如何替代所有事件?
当前回答
String.prototype.replace 所有 - ECMAScript 2021
新的 String.prototype.replaceAll() 方法将返回一个新的行,一个模式的所有比赛被替换。
const message = 'dog barks meow meow'; const messageFormatted = message.replaceAll('meow', 'woof') console.log(messageFormatted);
其他回答
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
要取代所有类型的字符,请尝试此代码:
假设我们需要发送“和 \ 在我的行中,然后我们将转换“到“和 \ 到“。
因此,这种方法将解决这个问题。
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);
};
使用
str = str.replace(new RegExp("abc", 'g'), "");
因此,新的RegExp(“abc”,“g”)创造了一个常见的表达,符合所有事件(“g”旗帜)的文本(“abc”)。第二部分是什么被取代,在你的情况下,空线(“). str 是线,我们必须将它,作为替代(...)只是返回结果,但不超过。
有一个方法可以使用新的替代All() 方法。
但您需要使用先进的浏览器或JavaScript运行时间环境。
您可以在这里查看浏览器兼容性。
如果使用图书馆是您的选择,那么您将获得与图书馆功能一起进行的测试和社区支持的好处。
// Include a reference to the string.js library and call it (for example) S.
str = S(str).replaceAll('abc', '').s;