[英]Replace all html attribute definitions that use single quotes with double quotes
我有一個 html 字符串,我想用雙引號替換用單引號設置的 html 屬性的任何實例。
例如,我想替換
<script src='foo.js'></script>
和
<script src="foo.js"></script>
但是,我希望在不影響 javascript 語句或 html 文本中的任何單引號的情況下執行此操作。
例如
<script> var foo = '67'; </script>
應該不受影響並且
<div id='foo'> 'hi' </div>
應該成為
<div id="foo"> 'hi' </div>
有什么簡單的方法可以做到這一點嗎?
對於一個給定的元素,用 jquery 選擇它,然后讀取它的外層 HTML 會這樣做,但我想一次對整個 html 頁面執行此操作。
謝謝!
嘗試這個:
var str = "<br style = 'width:100px'/> test link<a href=\"http://www\"></a>";
var regex = /<\w+\s*(\w+\s*=\s*(['][^']*['])|(["][^"]*["]))*\s*[\/]?>/g;
var rstr = str.replace(regex, function($0,$1,$2){
return $0.replace($2, $2.replace(/'/g, '"'));
});
console.log('replaced string = ' + rstr);
您可以參考它以嚴格匹配您的情況。
回答我自己的問題,因為我認為最簡單的解決方案是這個小提琴中顯示的內容,不需要 jquery 或正則表達式:
<html id="foo"></html>
var htmlString =
'<head>' +
'<script type="text/javascript" src=\'main.js\'></scr' + 'ipt>' +
'</head>' +
'<body onload=\'onLoad()\'>' +
'</body>' ;
document.getElementById('foo').innerHTML = htmlString;
console.log(document.getElementById('foo').outerHTML);
基本上,您只需要將 html 元素的內部 html 設置為沒有 html 標簽的 html 字符串,然后將 html 元素輸出到外部 html。
我認為這比使用正則表達式要簡單一些,盡管這是一個很棒的正則表達式 Mike :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.