0

I am getting text and some important words list from python script which I am displaying using flask in UI.

I wanted to highlight important keywords in text. Which works fine when I test it on w3scool compiler.

enter image description here

<body>

<p id="demo"></p>

<div id="vow_p"></div>
<script>
var vow = "Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come.";

var wordsToBold=["night","watcher"];

function makeBold(input, wordsToBold) {
   return input.replace(new RegExp('(\\b)(' + wordsToBold.join('|') + ')(\\b)','ig'), '$1<u><b>$2</u></b>$3');
}

document.getElementById("vow_p").innerHTML = makeBold(vow, wordsToBold);
</script>

</body>
</html>

Same code I have integrated in my flask app. Here problem is only one, first keyword getting highlighted rest keywords does not get any effect. Am I making any mistake?

app.py

app = Flask(name)

@app.route('/')
def index():
    return render_template('text-process.html')

in text-process.html

<script>
// var vow = {{ item }};
var someJavaScriptVar = '{{ wordres }}';
var wordsToBold =['reduced'];


function makeBold(input, wordsToBold) {
    return input.replace(new RegExp('(\\b)(' + wordsToBold.join(',') + ')(\\b)','ig'), '$1<mark>$2</mark>$3');
}

document.getElementById("vow_p").innerHTML = makeBold(someJavaScriptVar, wordsToBold);
</script>

1 Answer 1

1

change

wordsToBold.join(',')

to

wordsToBold.join('|')

The | in a regexp means »or« so /one|word|of|those/ matches: one OR word OR …

/one,word,of,those/ as created by your script matches the whole string.

Additionally

var wordsToBold =['reduced'];

contains only a single word, so matter if that get joined by | or ,, it will result only in (reduced), so match only that word.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, actually I saw when I add manual list of keywords in function. It is now highlighting all keywords. But when I dynamically take list from python script it does not do. It takes text content dynamically but not the keyword list.

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.