我想动态更改匹配文本的颜色,为此,以下乌尔都语文本代码不起作用,并且不更改匹配文本的颜色,而对于英语文本,它工作得很好。请任何解决方案。
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;
您遇到此问题是因为您的正则表达式不正确。
因为
\b
字边界与 Latin
脚本配合良好,但与 RTL
脚本和 Unicode
字符配合使用。
尝试将其替换为
g
(全局)和 u
(Unicode 字符)
const regex = new RegExp(`(${highlightWordsArray.join("|")})`, "gu")
如果您想了解更多,可以查看这篇文章