将文本和后面的字母替换为其他文本

时间:2015-08-03 09:06:53

标签: javascript jquery replace syntax-highlighting

我在jQuery中制作语法高亮显示,我希望能够显示转义(例如\n)。目前,我的代码只是将\替换为<span style="color:#3b73e3;">\\</span>(第一个\用于...嗯...转义)。我想要的是它是否可以用\替换<span style="color:#3b73e3;">\\(the escaped letter)</span>和以下字母。

当前.replace代码:

    String.prototype.replaceAllTxt = function() {
        return this.toString().replace(/\$slc/g, '*select')
                .replace(/\$/g, "!dol")
                .replace(/:/g, "$cln")
                .replace(/\//g, "$slh")
                .replace(/\./g, "$per")
                .replace(/@/g, "$at")
                .replace(/%/g, "$prc")
                .replace(/"/g, "*")
                .replace('*select', '<span id="select"></span>')
                .replace(/\*([^\*]+)\*/g, '<span style="color:#16630D">"$1"</span>')
                .replace(/\$cln/g, '<span style="color:#ff755d">:</span>')
                .replace(/\$at/g, '<span style="color:#ff26b6">@</span>')
                .replace(/\$prc/g, '<span style="color:#9e26ff">%</span>')
                .replace(/\$per/g, '<span style="color:#00bbff">.</span>')
                .replace(/\$slh/g, '<span style="color:#3b73e3;">/</span>')
                .replace(/\\/g, '<span style="color:#3b73e3;">\\</span>')
                .replace(/!dol/g, '<span style="color:#9b1940;font-weight:bold;">$</span>')
                .replace(/\$cln/g, ":")
                .replace(/\$slh/g, "/")
                .replace(/\$per/g, ".")
                .replace(/\$at/g, "@")
                .replace(/\$prc/g, "%")
                .replace(/\*/g, '"')
                .replace(/!dol/g, '$');
    };

到目前为止的一切:

String.prototype.replaceAllTxt = function() {
            return this.toString().replace(/\$slc/g, '*select')
                    .replace(/\$/g, "!dol")
                    .replace(/:/g, "$cln")
                    .replace(/\//g, "$slh")
                    .replace(/\./g, "$per")
                    .replace(/@/g, "$at")
                    .replace(/%/g, "$prc")
                    .replace(/"/g, "*")
                    .replace('*select', '<span id="select"></span>')
                    .replace(/\*([^\*]+)\*/g, '<span style="color:#16630D">"$1"</span>')
                    .replace(/\$cln/g, '<span style="color:#ff755d">:</span>')
                    .replace(/\$at/g, '<span style="color:#ff26b6">@</span>')
                    .replace(/\$prc/g, '<span style="color:#9e26ff">%</span>')
                    .replace(/\$per/g, '<span style="color:#00bbff">.</span>')
                    .replace(/\$slh/g, '<span style="color:#3b73e3;">/</span>')
                    .replace(/\\/g, '<span style="color:#3b73e3;">\\</span>')
                    .replace(/!dol/g, '<span style="color:#9b1940;font-weight:bold;">$</span>')
                    .replace(/\$cln/g, ":")
                    .replace(/\$slh/g, "/")
                    .replace(/\$per/g, ".")
                    .replace(/\$at/g, "@")
                    .replace(/\$prc/g, "%")
                    .replace(/\*/g, '"')
                    .replace(/!dol/g, '$');
        };
        function replaceText(oldText, newText, node){
            node = node || document.body; // base node

            var childs = node.childNodes, i = 0;

            while(node = childs[i]){
                if (node.nodeType == 3){ // text node found, do the replacement
                    if (node.textContent) {
                        node.textContent = node.textContent.replace(oldText, newText);
                    } else { // support to IE
                        node.nodeValue = node.nodeValue.replace(oldText, newText);
                    }
                } else { // not a text mode, look forward
                    replaceText(oldText, newText, node);
                }
                i++;
            }
        }
        function codeBox(el) {
            pasteHtmlAtCaret('$slc');
            $(el).css('color', '#153A7D').each(function () {
                setTimeout(function() {
                    var txt = $(el).text();
                    var newtxt = txt.replaceAllTxt();
                    $(el).html(newtxt);
                });
            });
            setTimeout(function() {
                $('#select').focus().select().remove();
            }, 1);
        }
        $.fn.codeBox = function () {
            $(this).css('color', '#153A7D').each(function () {
                var txt = $(this).text();
                var newtxt = txt.replaceAllTxt();
                $(this).html(newtxt);
            });
        };
        function wait(run, ms) {
            setTimeout(run(),ms);
        }
        function loop (run, ms) {
            setInterval(run(), ms);
        }
        function placeCaretAtEnd(el) {
            el.focus();
            if (typeof window.getSelection != "undefined"
                    && typeof document.createRange != "undefined") {
                var range = document.createRange();
                range.selectNodeContents(el);
                range.collapse(false);
                var sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            } else if (typeof document.body.createTextRange != "undefined") {
                var textRange = document.body.createTextRange();
                textRange.moveToElementText(el);
                textRange.collapse(false);
                textRange.select();
            }
        }
		function pasteHtmlAtCaret(html, selectPastedContent) {
    var sel, range;
    if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // only relatively recently standardized and is not supported in
            // some browsers (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            var firstNode = frag.firstChild;
            range.insertNode(frag);

            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                if (selectPastedContent) {
                    range.setStartBefore(firstNode);
                } else {
                    range.collapse(true);
                }
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        // IE < 9
        var originalRange = sel.createRange();
        originalRange.collapse(true);
        sel.createRange().pasteHTML(html);
        if (selectPastedContent) {
            range = sel.createRange();
            range.setEndPoint("StartToStart", originalRange);
            range.select();
        }
    }
}
function selectElementText(el, win) {
    win = win || window;
    var doc = win.document, sel, range;
    if (win.getSelection && doc.createRange) {
        sel = win.getSelection();
        range = doc.createRange();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (doc.body.createTextRange) {
        range = doc.body.createTextRange();
        range.moveToElementText(el);
        range.select();
    }
}
$(document).ready(function() {
            $('p').each(function () {
                $(this).html($(this).html().replace(/\n/g, "<br>"));
            });
            //$('code').each(function() {
            //    $(this).before('<span class="code" style="font-family:Source Code Pro, monospace;background-color:#e8e8e8;">'+$(this).text()+'</span>').remove();
            //    c
            // console.log ('code')
            //});
            $('code').codeBox();
            $("#edit").keypress(function() {
                setTimeout(function() {
                    codeBox("#edit");
                }, 1);
            });
            $('#highlight').click(function() {
                $("#code").codeBox();
            })
        });
.code {
  font-family:'Source Code Pro', monospace;
}
<script src="http://code.jquery.com/jquery-2.1.4.js"></script>
<pre data-syntax="default" id="code">$(document).ready(function() {
    alert ("The highlighting is ready. Email me at admin@example for more details.\nThis page has a 100% chance of loading.";
}

I would like for \n to look like </pre><span style="color:#3b73e3;">\n</span>, the same for \anything.
<div class="button" id="highlight">Highlight!</div>

JsFiddle:http://jsfiddle.net/zoweb/zuc5f7w8/

注意:上面代码段中的某些功能是从其他SO答案中获取的,而且很多功能都没有被使用。

1 个答案:

答案 0 :(得分:1)

您想要捕获下一个符号,这可以通过使用括号来完成:

function f(b: B) { }
f(new A());

这仅适用于转义序列(&#34; \\ n&#34;),因为普通&#39; \ n&#39;是一个角色。