(正则表达式)只替换<tag>和</tag>之间的文本?

时间:2012-02-23 18:50:13

标签: javascript html regex

我想在<tag></tag>内插入中文字符和数字(或字母)之间的空格。


EX1:

原始字符串:

<a href="http://example.com/漢字1234.html">it's a Chinese character漢字1234</a>

预期结果:

<a href="http://example.com/漢字1234.html">it's a Chinese character 漢字 12345</a>


EX2:

更复杂的原始字符串:

<div id="foo">
    <div class="bar1">
        <span>abcd漢字1234</span>
    </div>
    <div class="bar2">
        123漢字abcd
        <p>letters漢字<a href="http://example.com/漢字1234.html">42漢字answer</a></p>
    </div>
</div>

预期结果:

<div id="foo">
    <div class="bar1">
        <span>abcd 漢字 1234</span>
    </div>
    <div class="bar2">
        123 漢字 abcd
        <p>letters 漢字<a href="http://example.com/漢字1234.html">answer 漢字 42</a></p>
    </div>
</div>


这是我在JavaScipt中所做的:

function insert_space(text) {
    // I use [\u4E00-\u9FA5] to match Chinese characte
    text = text.replace(/([\u4E00-\u9FA5])([a-z0-9])/ig, '$1 $2');

    text = text.replace(/([a-z0-9])([\u4E00-\u9FA5])/ig, '$1 $2');

    return text;
}

function replaceEntry() {
    var target_tags = ['div', 'p', 'li', 'td', 'span', 'a', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
    var body_tag = $('body');
    var raw_text;
    var format_text;

    for (var i = 0; i < target_tags.length; i++) {
        var target_tag = target_tags[i];

        $(target_tag, body_tag).each(function() {
            var has_children = false;

            console.log('\n');
            console.log(target_tag + ' begin');

            raw_text = $(this).html();

            console.log(raw_text);

            format_text = insert_space(raw_text);

            $(this).html(format_text);

            console.log(target_tag + ' end');
            console.log('\n');
        });
    }
}

replaceEntry();

但是这段代码无法处理上面的那两个例子。

我需要一个忙。非常感谢。


PS。

我将此代码放入Google Chrome扩展程序中,例如:

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(tab.id, {file: 'js/libs/jquery-1.7.1.min.js'});
    chrome.tabs.executeScript(tab.id, {file: 'js/auto_spacing.js'});
});



更新:

我找到了一个解决方案:使用XML XPath

var current_documant = window.document;

var xpath_query = '//text()[normalize-space(.)][translate(name(..),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")!="script"][translate(name(..),"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz")!="style"]';

var nodes = current_documant.evaluate(xpath_query, current_documant, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

var nodes_length = nodes.snapshotLength;

for (var i = 0; i < nodes_length; ++i) {
    var current_node = nodes.snapshotItem(i);

    // http://www.w3school.com.cn/xmldom/dom_text.asp
    current_node.data = insert_space(current_node.data);
}

1 个答案:

答案 0 :(得分:1)

function doReplace( str ) {
    var rchinese = /([\u4E00-\u9FA5]+)/g;

    var root = document.createElement("div");
    root.innerHTML = str;

    ['div', 'p', 'li', 'td', 'span', 'a', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'].forEach( function( tagName ) {
        [].forEach.call( root.getElementsByTagName( tagName ), function( elem ) {
            [].forEach.call( elem.childNodes, function( node ) {
                if( node.nodeType === 3 ) {
                    node.nodeValue = node.nodeValue.replace( rchinese, " $1 ");
                }
            });
        });
    });

    return root.innerHTML;
}

结果:

var test = '<a href="http://example.com/漢字1234.html">it\'s a Chinese character漢字1234</a>';
doReplace(test);
//<a href="http://example.com/漢字1234.html">it's a Chinese character 漢字 1234</a>