我有一个 HTML 页面,其中包含英语单词和波斯语单词。我想知道如何检测英语单词并更改它们的颜色,以及检测波斯语单词并将它们的颜色更改为不同的颜色。
这些词是动态的并且可以更改。我想通过 jQuery 或 JavaScript 检测它们并更改颜色。
例如,给定以下文本:
Hi سلام بر this این text can be برای اولین ...
我想用红色显示这些词:
Hi, This, Text, can, be,
这些蓝色的字:
بر, سلام, این, برای, اولین
最佳答案
使用字符代码怎么样?
英文字母位于前 255 个字符内,但波斯语字母不在其中。
html
<p>Hi سلام بر this این text can be برای اولین.</p>
JavaScript
jQuery(function($) {
$("p").each(function(){
this.innerHTML = $(this).text().replace(/\S+/g, function (word) {
var span = document.createElement("span");
span.className = "word ";
span.className += isEnglish(word) ? 'english' : '';
span.className += isPersian(word) ? 'persian' : '';
span.appendChild(document.createTextNode(word));
return span.outerHTML;
});
});
function isEnglish(word){
return word.charCodeAt(0) < 255;
}
function isPersian(word){
return word.charCodeAt(0) > 255;
}
});
关于javascript - 如何使用 JavaScript 在网页上以不同的颜色显示英语和波斯语单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17526454/