在代码<a> (regex with variable)

时间:2017-04-20 16:04:28

标签: regex

function Selection () {
               
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    
   var result = html.indexOf("href");
    if (result != -1) {
window.getSelection().empty();
                   window.getSelection().removeAllRanges();
                  
    } else {
    var textofclassText = $('.text').html();
    //var patt1 = /id=\"load([\s\S]*?)+[selectedTexthtml]/g;
    var result_2;
    //var result_2 = textofclassText.search(patt1);
    if(result_2 != "null") {
window.getSelection().empty();
                   window.getSelection().removeAllRanges();
    }
    
    }

        }     
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>

<div class="text" onmouseup="Selection()">
You &nbsp;
<br><a class="good" data-id="3" href="#load" id="load3">are very </a> important for us.
<br>So we're offering you 
<br><a class="good" data-id="4" href="#load" id="load4"> win-win</a> option.
<br>You will get 2 refrigerators if you buy one

</div>

</body>
</html>

I need to remove selection if the selected text contains "a" tag. If I start to select link-text from left I will get only text "are very", so I need to find first match in all class ".text". I can't get how to use variable in that regex, because when I try to build string from variables it doesn't work.

var patt1 = new RegExp("id=\"load([\s\S]*?)" + html, "g");
var result = textofclassText.search(patt1);

0 个答案:

没有答案