I want to change color of matched text dynamically, for this the following code for Urdu text not working and not changing the color of matched text, while for English text it's working perfectly. Any solution please.
import React from "react";
const App = () => {
const content = "علی اور بوب چارلی سے ملاقات کے لئے گئے۔ بعد میں، علی نے بوب اور چارلی کو مدعو کیا۔";
const urduWordsToHighlight = ["علی", "بوب", "چارلی"]; // Array of words to highlight
// Function to wrap matched words with blue-colored spans
const highlightUrduWords = (text, highlightWordsArray) => {
const regex = new RegExp(`\\b(${highlightWordsArray.join("|")})\\b`, "g"); // Match exact words
const parts = text.split(regex); // Split text into matched and unmatched parts
return parts.map((part, index) => {
if (highlightWordsArray.includes(part)) {
// If the part matches, wrap it in a span with blue color
return (
<span key={index} style={{ color: "blue", fontWeight: "bold" }}>
{part}
</span>
);
}
// Return unmatched parts as plain text
return part;
});
};
return (
<div>
<h1> ہائی لائٹ </h1>
<p style={{ fontFamily: "Noto Nastaliq Urdu, Arial, sans-serif" }}>
{highlightUrduWords(content, urduWordsToHighlight)}
</p>
</div>
);
};
export default App;
You are facing this issue because your regular expression is not correct.
That's because the \b
word boundary works well with Latin
string but struggles with RTL
and Unicode
character.
Try to replace it with g
for global and u
for Unicode chars
const regex = new RegExp(`(${highlightWordsArray.join("|")})`, "gu")
You can check this article if you wanna discover more