使用jquery将除文本字段和文本区域外的所有html标记中的所有指定符号转换为另一个符号

convert all specified symbol to another in all html tags except textfields and textareas with jquery

本文关键字:符号 文本 jquery 转换 另一个 区域 使用 html 字段      更新时间:2023-09-26

我想将所有html元素中的所有拉丁数字转换为阿拉伯数字,除了textfields,textarea标记和jquery。

arabic digits=('۰','۱','۲','۳','۴','۵','۶','۷','۸','۹');
latin digits=('0','1','2','3','4','5','6','7','8','9');

我知道regex是将所有阿拉伯语转换为数字的解决方案,但我的困难是只转换指定html标记中的文本。

从您对该问题的评论中,听起来您不想要只想要divspanp元素,而是想要所有不是表单字段的元素。

您可以使用循环浏览页面上的所有非表单字段元素

$("*:not(textarea, input, select)").each(function() {
    // ...do something here...
});

在函数中,您可以使用.contents()(获取所有子节点,包括文本节点)、.filter(过滤掉除文本节点外的所有内容)和.each(循环遍历其余子节点)更新元素的文本(而不是其子元素中的任何文本);则更新CCD_ 7以更新文本节点的文本:

$("*:not(textarea, input, select)").each(function() {
    $(this).contents().filter(function() {
        return this.nodeType === 3; // 3 = text node
    }).each(function() {
        this.nodeValue = this.nodeValue.replace(/*...your regex replacement here...*/);
    });
});

你似乎说你知道如何用regex进行替换,但下面你建议你不要。这里有一个相当简单的方法:

一次,在前面:

var arabicToLatinMap = {
    "۰": "0",
    "۱": "1",
    "۲": "2",
    "۳": "3",
    "۴": "4",
    "۵": "5",
    "۶": "6",
    "۷": "7",
    "۸": "8",
    "۹": "9"
};
var arabicRegEx = /[۰۱۲۳۴۵۶۷۸۹]/g;

然后在相关位置:

this.nodeValue = this.nodeValue.replace(arabicRegEx, function(digit) {
    return arabicToLatinMap[digit];
});

旁注:0、1、2、3等不是拉丁数字。有趣的是,它们是阿拉伯语数字,只是它们是西部阿拉伯语,而不是现在中东使用的东部阿拉伯数字。因此,这实际上是一个东西方阿拉伯数字转换器。:-)大约在9-10世纪,西方世界的数字来自阿拉伯世界杰出的数学家。