Skip to content

Instantly share code, notes, and snippets.

@LeiHao0
Last active May 17, 2019 06:14
Show Gist options
  • Save LeiHao0/1cbe14dc867187164e3aff69ffbc4450 to your computer and use it in GitHub Desktop.
Save LeiHao0/1cbe14dc867187164e3aff69ffbc4450 to your computer and use it in GitHub Desktop.
Javascript camelize string
<!DOCTYPE html>
<html>
<body>
<textarea id="from" rows="5" cols="50">
What's your name?
Let's go!!!
Sorry, I can’t hear you...
</textarea>
<button type="button" onclick="camelize()">camelize</button>
<textarea id="toCamel" rows="5" cols="50"></textarea>
<textarea id="toJson" rows="10" cols="100"></textarea>
</body>
</html>
<script>
String.prototype.camelize = function () {
return this.trim().replace(/[^a-zA-Z0-9 ]/g, "").replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match,
index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index == 0 ? match.toLowerCase() : match.toUpperCase();
});
}
function camelize() {
from = document.getElementById("from").value.split('\n').map((l) => {
return l.trim()
}).filter((l) => {
return l
})
to = from.map((l) => {
return l.camelize()
})
document.getElementById("toCamel").value = to.join('\n')
toJson = '{\n'
for (i = 0; i < from.length; i++) {
toJson = toJson + to[i] + ": " + "\"" + from[i] + "\",\n"
}
console.log(toJson);
document.getElementById("toJson").value = toJson + "}"
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment