jQuery toggleClass example
Toggle class name on click in jQuery
by guydog28
HTML
<h1>Text to JSON Parser</h1>
<form onsubmit="return parseTextToJson()">
<label for="text-input">Paste your text here:</label><br>
<textarea id="text-input" rows="10" cols="50"></textarea><br>
<input type="submit" value="Parse to JSON">
</form>
<h2>JSON Output:</h2>
<pre id="json-output"></pre>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
JavaScript
function parseTextToJson() {
// Retrieve the text from the textarea
var text = document.getElementById('text-input').value;
// Parse the text into JSON
// Split text based on the question number (e.g., "1.")
var questions = text.trim().split(/\n(?=\d+\.\t)/).map(function(questionBlock) {
var lines = questionBlock.trim().split('\n');
var questionText = lines[0].substring(lines[0].indexOf('\t') + 1).trim();
var options = {};
var answerKey = '';
lines.slice(1, -1).forEach(function(line) {
var match = line.match(/•\s([a-d])\)\s(.*)/);
if (match) {
var key = match[1];
var optionText = match[2];
options[key.toUpperCase()] = optionText;
}
});
var answerMatch = lines[lines.length - 1].match(/•\sAnswer:\s([a-d])\)/);
if (answerMatch) {
answerKey = answerMatch[1].toUpperCase();
}
return { question: questionText, options: options, answer: answerKey, selected: null };
});
// Display the JSON result in the output container
document.getElementById('json-output').textContent = JSON.stringify(questions, null, 4);
// Prevent form submission
return false;
}