首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >匹配引号中的换行符

问匹配引号中的换行符
EN

Stack Overflow用户
提问于 2016-03-26 20:34:40
回答 2查看 548关注 0票数 0

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

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

(向任何其他regex/non解决方案开放!)

代码语言:javascript
复制
<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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-03-26 21:36:25

下面是进行转换的一个小片段:

​

代码语言:javascript
复制
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);
}
代码语言:javascript
复制
textarea { width: 25em; height: 10em; float:left}
代码语言:javascript
复制
<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替换将立即将&转义为&amp;。

票数 0
EN

Stack Overflow用户

发布于 2016-03-26 21:41:50

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

你想改变规则而不是贪婪。这里有一篇很好的文章对此进行了描述:

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36240592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档