I'm very slowly learning Javascript and am having difficulty implementing a for loop over regex matches.
I'm working in an express.js setup, with the following in my index.js
var express = require('express');
var router = express.Router();
// the text block against which I am running the regex
var para = "We have insisted on strict scrutiny in every context, even for so-called “benign” racial classifications, such as race-conscious university admissions policies, see Grutter v. Bollinger, 539 U.S. 306, 326 (2003), race-based preferences in government contracts, see Adarand, supra, at 226, and race-based districting intended to improve minority representation, see Shaw v. Reno, 509 U.S. 630, 650 (1993). Daniel added the following test case to the string: Crawford v. Washington, 123 U.S. 123, 123 (2016)."
// regex
var regex = /(\w+\sv.\s\w+,\s\d*\s?[\w.]*[\d,\s]*\(\d{4}\))/ig;
var regexTwo = /\w+\s/ig;
// Store the matches
var matches = para.match(regex);
var matchesTwo = para.match(regexTwo);
// the offending loop
for (var i = 0; i < matches.length; i += 1) {
router.get('/', function(req, res) {
res.render('index', { matches, matchesTwo, i }) });
};
module.exports = router;
I'm using Jade for the HTML and my index.jade file looks like this:
extends layout
block content
body
h1 CaseSpy
p I found the following U.S. cases in the text you provided me with:
ul
li #{matches}
p I found the following other terms in the text you provided me with:
ul
li #{matchesTwo}
The code works, insofar as it matches what I want it to match against. The problem I'm having is that all of the matches are getting bundles up on the same line, so the html output looks like this:
Output
I found the following U.S. cases in the text you provided me with:
- Grutter v. Bollinger, 539 U.S. 306, 326 (2003),Shaw v. Reno, 509 U.S. 630, 650 (1993),Crawford v. Washington, 123 U.S. 123, 123 (2016)
The output I'm looking for is:
Desired Output
I found the following U.S. cases in the text you provided me with:
- Grutter v. Bollinger, 539 U.S. 306, 326 (2003)
- Shaw v. Reno, 509 U.S. 630, 650 (1993)
- Crawford v. Washington, 123 U.S. 123, 123 (2016)
I've tinkered with the for loop endlessly and have tried this sort of method but keep hitting errors:
for (var i = 0; i < matches.length; i += 1) {
document.body.innerHTML += matches[i] + '<br>';
}
I just can't seem to crack this. I know I'm doing something fundamentally wrong, I just don't know what.
Many thanks.