Skip to content

Instantly share code, notes, and snippets.

@grahameger
Created February 14, 2018 00:07
Show Gist options
  • Save grahameger/3fdddf7704eb4a04a58cf27bef2b1b0d to your computer and use it in GitHub Desktop.
Save grahameger/3fdddf7704eb4a04a58cf27bef2b1b0d to your computer and use it in GitHub Desktop.
<!-- Graham Eger -->
<!-- grahameger.com -->
<!-- [email protected] -->
<!DOCTYPE html>
<html>
<head>
<title>StringSum</title>
<script type="text/javascript">
function parseString() {
// Get the string from the form.
var input = document.getElementById("a1").value;
// Regex to match integers
// The regex matches '-' optionally as well as all digits [0-9] required
var regex = /-?\d+/g;
// Convert them into integers and sum them
var total = input.match(regex).reduce(function(prev, num) {
return prev + parseInt(num);
}, 0);
// set a2 to be the total
document.getElementById("a2").text = total;
}
</script>
</head>
<body>
<h1>StringSum</h1>
Enter String:<input type="text" id="a1"><br>
<button onclick="parseString()">SumString</button>
<p><a id ="a2"></a></p>
</body>
<footer><a href="https://grahameger.com">grahameger.com</a></footer>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment