[英]Javascript library to compare 2 html string like freecodecamp
我有一个项目,我们在其中比较原始代码和用户编写的代码。 用户可以编写代码,然后单击按钮,我们必须将编写的代码与原始代码进行比较。
我在字符串中既有原始代码又有新代码
originalHtml: <html><body style='color:white;background:purple;'></body></html>
newHtml: <html> <body style="background:purple;color:white;"> </body> . </html>
<html> <body style="background:purple;color:white;"> </body> . </html>
这里要记住三件事
1)空格(不应显示空格的差异)
2) '
和"
(不应比较引号,两者均在HTML中有效)
3)属性顺序(只应针对缺少的属性显示差异,忽略属性顺序)
任何建议或替代解决方案将不胜感激。
您可以将它们全部转换为一个制服并进行比较。 例:
'
到"
获取属性的示例cheerio:
var cheerio = require('cheerio');
var yourString = `<html><body attr2='hi' attr1='hello' style='color:white;background:purple;'></body></html>`;
var $ = cheerio.load(yourString);
var yourAttrs = $('body')[0].attribs;
var sorted = {};
Object.keys(yourAttrs).sort().forEach(function(key) {
sorted[key] = yourAttrs[key];
});
console.log(sorted);
我为您创建了一支密码笔,这将解决您的问题。
https://codepen.io/bearnithi/pen/KEPXrX
const textArea = document.getElementById('code'); const btn = document.getElementById('checkcode'); const result = document.getElementById('result'); let originalHTML = `<html><head> <title>Hello </title> </head><body> <p class="hello"></p> </body> </html>` btn.addEventListener('click', checkCode); function checkCode() { let newHTMLCode = textArea.value.replace(/\\s/g,""); let oldHTMLCode = originalHTML.replace(/\\s/g,""); if(newHTMLCode === oldHTMLCode) { console.log(true); result.innerHTML = 'TRUE'; } else { console.log(false); result.innerHTML = 'FALSE'; } }
<textarea id="code"> </textarea> </br> <button id="checkcode">Check Code</button> <p id="result"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.