Skip to content

[Tutorial] Bug in example code 'Add default class for each HTML element' - adding classes only to first element #1026

Open
@wykopx

Description

On the tutorial page:

https://showdownjs.com/docs/tutorials/add-default-class-to-html/

The code works only for first occurence of each tag in the classMap.

const classMap = {
  a: 'exampleClass'
}

So if you have let's say two different list items:

<a> example 1 </a>
<a> example 2 </a>

it will add classes only to the first one because of the buggy RegExp

<a class="exampleClass"> example 1 </a>
<a> example 2 </a>

Image

There is an issue with the code. The line

regex: new RegExp(`<${key}(.*)>`, 'g'),

should be replaced with corrected RegExp version:

regex: new RegExp(`(?:<${key}>)|(?:<${key} (.*?)>)`, 'g'),

Code that adds classes in all elements in markdown text:

const bindings = Object.keys(classMap)
  .map(key => ({
  	type: 'output',
	regex: new RegExp(`(?:<${key}>)|(?:<${key} (.*?)>)`, 'g'),
  	replace: `<${key} class="${classMap[key]}" $1>`
  }));

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions