Skip to content

Instantly share code, notes, and snippets.

@fionera
Created April 7, 2023 00:16
Show Gist options
  • Save fionera/94c002c7fa822d4226982ea25b51e294 to your computer and use it in GitHub Desktop.
Save fionera/94c002c7fa822d4226982ea25b51e294 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Random Hex Colors in XML</title>
</head>
<body>
<label for="file-input">Select XML file:</label>
<input type="file" id="file-input">
<button id="randomize-btn" disabled>Randomize Hex Colors</button>
<br><br>
<div id="output"></div>
<script>
function generateRandomHexColor() {
const hexChars = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += hexChars[Math.floor(Math.random() * hexChars.length)];
}
return color;
}
function replaceHex(match) {
let oldHex = match[0];
let newHex = generateRandomHexColor();
return isValidHexColor(newHex) ? newHex : oldHex;
}
function isValidHexColor(hexColor) {
return /^#(?:[0-9a-fA-F]{3}){1,2}$/.test(hexColor);
}
function modifyHexColorsInXml(xmlString) {
let modifiedString = xmlString.replace(/#[0-9a-fA-F]{3,6}/g, replaceHex);
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(modifiedString, "application/xml");
let xmlStringModified = new XMLSerializer().serializeToString(xmlDoc);
return xmlStringModified;
}
let fileInput = document.getElementById('file-input');
let randomizeBtn = document.getElementById('randomize-btn');
let outputDiv = document.getElementById('output');
fileInput.addEventListener('change', () => {
randomizeBtn.disabled = false;
});
randomizeBtn.addEventListener('click', () => {
let file = fileInput.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = () => {
let xmlString = reader.result;
let xmlStringModified = modifyHexColorsInXml(xmlString);
outputDiv.innerText = xmlStringModified;
};
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment