0

My code right now is

const replace = (note) => {
    return DOMPurify.sanitize(
        note.replace(
            /\S/g,
            "<span class='letter' style='display: inline-block'>$&</span>"
        )
    )
};

as you can see in the span, I'm setting style as display inline-block directly. However instead, I want to set the style as some kind of variable like so:

const test = (note, style) => {
    const styles = {display: 'inline-block'};
    return DOMPurify.sanitize(
        note.replace(
            /\S/g,
            "<span class='letter' style={styles}>$&</span>"
        )
    )
};

but this isn't working because the {styles} inside the span doesn't know that I'm referring to my styles variable. Does anyone know the proper syntax to make this work?

2
  • "<span class='letter' style='" + styles + "'>$&</span>". But, styles should be declared like this: const styles = "display:inline-block;" Commented Jun 19, 2020 at 18:49
  • or `<span class='letter' style=${styles}>$&</span>` Commented Jun 19, 2020 at 18:50

2 Answers 2

1
const test = (note, style) => {
    const styles = "display:inline-block;";
    return DOMPurify.sanitize(
        note.replace(
            /\S/g,
            "<span class='letter' style=" + styles + ">$&</span>"
        )
    )
};

You can do it this way or this way:

const test = (note, style) => {
    const styles = "display:inline-block;";
    return DOMPurify.sanitize(
        note.replace(
            /\S/g,
            `<span class='letter' style=${styles}>$&</span>`
        )
    )
};
Sign up to request clarification or add additional context in comments.

1 Comment

styles needs to be declared as: const styles = "display:inline-block;"
0

You can use template literals:

const test = (note, style) => {
    const styles = "display:inline-block;";
    return DOMPurify.sanitize(
        note.replace(
            /\S/g,
            `<span class='letter' style=${styles}>$&</span>`
        )
    )
};

MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

1 Comment

styles needs to be declared as: const styles = "display:inline-block;"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.