Named Entity Recognition is a crucial technology for NLP. Whatever you’re doing with text, you usually want to handle names, numbers, dates and other entities differently from regular words. To help you make use of NER, we’ve released displaCy-ent.js. This post explains how the library works, and how to use it.
Here’s an example of a text rendered by displaCy ENT:
The labels are displayed and styled using only CSS selectors — and you can do some pretty powerful stuff with that. You’ll see a few examples later on.
To use displaCy ENT, include displacy-ent.js and initialize a new
instance specifying the API and settings. The
parse(text, model, ents) method
renders a parse generated by
spaCy’s services, which you can
download and run for free.
For a full list of available settings, see the
Alternatively, you can also use
render(text, spans, ents) to manually render a
JSON-formatted set of entity spans returned from our
Let’s say you want to add entity visualisation to a bunch of text on your site. You can do this by replacing the content of your container with the visualised output of displaCy ENT once the document has loaded:
Note that this only grabs the
textContent and ignores line breaks, paragraphs
and other HTML tags. As a workaround, you could replace line beaks and pargraphs
with newlines in the container’s
innerHTML and then grab its
In general, I’d recommend to only use displaCy ENT on plain, unformatted text. If you’re working with user input or other unpredictable content, opt for a library to sanitise HTML and prevent Cross-Site-Scripting (XSS).
displaCy ENT wraps the entities in the HTML5
highlighted text. Each entity is
assigned the data attribute
returned by the server, slices the original text into fragments and, if an
entity should be visualised, wraps it in a
tag and adds the right data
attribute. The data attributes are then displayed after the entity in CSS using
With CSS, you have almost infinite possibilities to present the entities. Here are a few examples with different colours, borders and hover effects:
There’s another cool thing you can do with advanced selectors: You can make it only show the entity label for the first instance, or rather, hide all other ones and only show them on hover:
The trick here is the
element ~ element selector that selects all elements
following another element. Basically, we’re adding the label to all entities
and then hiding it for all entities with
another one, i.e. all except for the first.
This needs to be done for all occuring entity types. In my example, I used a simple Sass loop to automate this:
In the future, we’re planning to add support for more annotation formats like Google’s NLP API and CoreNLP. I’d also love to release more CSS themes for different entity styles. If you’d like to contribute one, check out the current Sass template here and feel free to submit a pull request.