正则表达式只替换字母数字字符串

时间:2014-11-20 12:30:49

标签: javascript regex

我正在开发一个工具,用右键单击上下文菜单中选择的选项标记字母数字单词。当选择一组单词并且其中包含一些特殊字符时,我遇到了问题。

我正在使用此网站上的RegEx:/(\s[a-zA-Z0-9]+)/g

要重现此问题,请从文本中选择123b @#$@#$@#$@#$ a,然后右键单击并选择任意选项。预期结果分别为[TAG] 123b @#$@#$@#$@#$ [TAG] a

此外,如果我尝试标记以下完整字符串,则该功能不起作用:
rahul@gmail.com 123a % / ! @$# % % %^* && ^ Lorem ipsum
预期结果为:
[TAG] rahul@gmail.com [TAG] 123a % / ! @$# % % %^* && ^ [TAG] Lorem [TAG] ipsum

理想情况下,它应标记123abcabc12312ab3等字符串,并带有任意数量的数字和字母。如果选择了类似电子邮件地址的字符串,那么也应该对其进行标记。

我该如何解决这个问题?

jsFiddle

HTML:

<p contenteditable="true">rahul@gmail.com 123a % / ! @$# % % %^* && ^ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer augue tortor, dictum a turpis non, dapibus vehicula neque. 123b @#$@#$ a quam vel cursus. Duis at mattis quam, ornare consequat enim. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer augue tortor, dictum a turpis non, dapibus vehicula neque. Aliquam dictum a quam vel cursus. Duis at mattis quam, ornare consequat enim. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p>

JS:

function replaceText(selectedText, selectedTag){
    if(selectedText == "")
        return false;
    if(selectedText.match(/^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/))
        replacedText = selectedText.replace(/(\s[a-zA-Z0-9]+)/g, " " + selectedTag + " " + "$1");
    else
        replacedText = selectedTag + " " + selectedText.replace(/(\s[a-zA-Z0-9]+)/g, " " + selectedTag + " " + "$1");
    originalText = $('p').html();
    newText = originalText.replace( new RegExp(selectedText,"g") , replacedText);
    $('p').html(newText);
}

2 个答案:

答案 0 :(得分:1)

以下是更新后的代码。

注意:我更新了其他部分,先删除所有特殊字符,然后用 [tag] + string 替换字符串的所有匹配项。

HTML:

<p contenteditable="true">rahul@gmail.com 123a % / ! @$# % % %^* && ^ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer augue tortor, dictum a turpis non, dapibus vehicula neque. 123b @#$@#$ a quam vel cursus. Duis at mattis quam, ornare consequat enim. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer augue tortor, dictum a turpis non, dapibus vehicula neque. Aliquam dictum a quam vel cursus. Duis at mattis quam, ornare consequat enim. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.</p>

JavaScript的:

var selectedTag, selectedText, originalText, newText, replacedText, selectedTextArray;

function getSelectedText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}

function replaceText(selectedText, selectedTag){
    if(selectedText == "") {
        return false;
    }
    else {
        selectedText = selectedText.replace(/[^a-zA-Z0-9 ]/g,'');
        selectedText = selectedText.replace(/\s{2,}/g, ' ');
        selectedTextArray = selectedText.split(" ");
    }
    if(selectedTextArray.length > 0) {
        var selectedTextPart = '';
        originalText = $('p').html();
        newText = originalText;
        for(var i=0; i<selectedTextArray.length; i++) {
            selectedTextPart = selectedTextArray[i];
            selectedTextPart = new RegExp("\\b"+selectedTextPart+"\\b", "g");
            replacedText = selectedTag+' '+'$&';
            newText = newText.replace( selectedTextPart , replacedText);
        }
        $('p').html(newText);
    }
}

$.contextMenu({
    selector: 'p', 
    callback: function(key, options) {
        selectedTag = key;
        selectedText = $.trim(getSelectedText());
        replaceText(selectedText, selectedTag);
    },
    items: {
        "[ORG]": {name: "[ORG]"},
        "[PER]": {name: "[PER]"},
        "[LOC]": {name: "[LOC]"}
    }
});

答案 1 :(得分:1)

保持简单,他们说。

我打破了以下类别中的每一个字:

  1. 字母数字
  2. 字母数字后跟。或者,(如句子所示)
  3. 电子邮件
  4. 然后我添加了标签并将其替换为正文。多数民众赞成!

    function replaceText(selectedText, selectedTag){
        if(selectedText == "") {
            return false;
        }
        else{
            var selectedTextArray = selectedText.split(" ");
    
            originalText = $('p').html();
    
            selectedTextArray.forEach(function(item){
                if(item.match(/^[a-zA-Z0-9]+$/) // alphanumeric
                   || item.match(/^[a-zA-Z0-9.,]+$/) // alphanumeric followed by . or ,
                   || item.match(/([a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+))/) // email               
                    ){
                        originalText = originalText.replace(new RegExp("\\b" + item + "\\b","g") , selectedTag + " " + item);
    
                    }                 
            });
            newText = originalText;
        }
    
        $('p').html(newText);
    }
    

    jsFiddle