如何使用JavaScript在网页上以不同颜色显示英语和波斯语单词

How can I display English and Persian words on a web page in different colours using JavaScript?

本文关键字:显示 颜色 英语 单词 波斯语 JavaScript 何使用 网页      更新时间:2023-09-26

我有一个HTML页面,其中包含英语单词和波斯语单词。我想知道如何检测英语单词并改变它们的颜色,如何检测波斯单词并将它们的颜色改变为不同的颜色。

这些单词是动态的,可以更改。我想通过jQuery或JavaScript检测它们并更改颜色。

例如,给定以下文本:

Hi سلام بر this این text can be برای اولین ...

我想用红色显示这些单词:

Hi, This, Text, can, be, 

这些蓝色的单词:

بر, سلام, این, برای, اولین 

使用char代码怎么样?

英文字母在前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;
    }
});

jsFiddle

或者你能给我举个例子吗?

好吧:

// Find text in descendents of an element, in reverse document order
// pattern must be a regexp with global flag
//
function findText(element, pattern, callback) {
    var nonHtmlTags= {textarea:1, option:1, script:1, style:1, svg:1, math:1};
    for (var childi= element.childNodes.length; childi-->0;) {
        var child= element.childNodes[childi];
        if (child.nodeType==1 && !(child.tagName in nonHtmlTags)) {
            findText(child, pattern, callback);
        } else if (child.nodeType==3) {
            var matches= [];
            var match;
            while (match= pattern.exec(child.data))
                matches.push(match);
            for (var i= matches.length; i-->0;)
                callback.call(window, child, matches[i]);
        }
    }
}
// Find text and wrap with span elements
//
function highlightText(element, pattern, className) {
    findText(document.body, pattern, function(node, match) {
        var span= document.createElement('span');
        span.className= className;
        node.splitText(match.index+match[0].length);
        span.appendChild(node.splitText(match.index));
        node.parentNode.insertBefore(span, node.nextSibling);
    });
}
highlightText(document.body, /[a-z]+/gi, 'english-word');
highlightText(document.body, /['u0600-'u06FF]+/gi, 'persian-word');

请注意,英语和波斯语regexp非常幼稚,对于不寻常的字符(如拉丁ï或阿拉伯语)会失败。想出一个更完整的表达方式是初学者的一项练习。