匹配引号内的换行符

时间:2016-03-26 20:34:41

标签: javascript regex xml

我正在寻找一种解决方案来替换Javascript中XML属性(XML字符串)中的换行符。 (尝试用
替换,以便在解析XML时不会丢失换行符。

注意:字符串中还有其他换行符,例如在<main> .. </body>

之后

(对任何其他正则表达式/非正则表达式解决方案开放!)

<main>
<head/><body><note text="Load"> 
<note text="2 Newlines at the end of this    

newline"/>
</body>
</main>

我所拥有的只是这件可怕的事"[\s\S]*?([\r\n]+)[\s\S]*?"

https://regex101.com/r/vE2lD7/2

2 个答案:

答案 0 :(得分:0)

以下是进行转换的小片段:

styles
Sidebar
function convert(xmlStr) {
    var xml = document.createElement('xml');
    xml.innerHTML = xmlStr;

    [].forEach.call(xml.querySelectorAll('note[text]'), function (note) {
        note.setAttribute('text',
            note.getAttribute('text').replace(/\r?\n/g,'@#10'));
    });

    return xml.innerHTML.replace(/@#10/g, '&#10');
}

// I/O
var button = document.querySelector('button');
var input = document.querySelector('textarea');
var output = document.querySelector('pre');

// click handler
button.onclick = function () {
    output.textContent = convert(input.value);
}

请注意,立即替换textarea { width: 25em; height: 10em; float:left}会导致<textarea><main> <head/><body><note text="Load"> <note text="2 Newlines at the end of this newline"/> </body> </main></textarea> <button>convert</button> <pre></pre>转义为&#10

答案 1 :(得分:0)

https://regex101.com/r/vE2lD7/3

你想改变正则表达式而不是贪婪。这是一篇描述它的好文章:

https://docs.oracle.com/javase/tutorial/essential/regex/quant.html