用特殊字符替换子字符串

时间:2019-06-23 06:17:38

标签: javascript regex replace

我有一个字符串,其中包含一些用特殊字符包裹的子字符串。 这是我的代码:

function showLinkSummary() {
    jQuery("input[name='summary']").prop("disabled", true);
    jQuery.ajax({
        type: "POST",
        url: "${url}",
        success: function (data, textStatus) {
            jQuery("input[name='summary']").prop("disabled", false);
            jQuery("#summaryOfLinks").html(data);
            jQuery("#summaryOfLinks").removeClass("hiddenPopup");
            jQuery("#summaryOfLinks").addClass("shownPopup");
            jQuery("#grayOut").removeClass("hiddenPopup");
            jQuery("#grayOut").addClass("shownPopup");
        },
        error: function (jqXHR, textStatus, errorThrown) {
            jQuery("#summaryOfLinks").html('Error:'  + errorThrown + ' with Status: ' + textStatus);
        }
    });
    return false;
}

代码为我提供了var p = 'The quick brown fox jumps over the lazy [dog]. If the [dog] reacted, was it really lazy?'; var regex = /[\\[dog\\]]/g; console.log(p.replace(regex, 'ferret')); 的输出,但我期望The quick brown fox jumps over the lazy ferretdogferret. If the ferretdogferret reacted, was it really lazy?

2 个答案:

答案 0 :(得分:6)

只需删除整个模式周围的字符集,然后匹配\[dog\]

var p = 'The quick brown fox jumps over the lazy [dog]. If the [dog] reacted, was it really lazy?';

var regex = /\[dog\]/g;

console.log(p.replace(regex, 'ferret'));

答案 1 :(得分:2)

您可以只使用标准JS并按以下方式进行处理。

let txt = 'The quick brown fox jumps over the lazy [dog]. If the [dog] reacted, was it really lazy?'

let txt1 = txt.split(' ')
txt1.map((word, i) => word.includes('dog') ? txt1[i]='ferret':null )
let sentence = txt1.join(' ')

console.log(sentence)