有没有一般的下标函数

Is there any generic function for subscripting?

本文关键字:下标 函数 有没有      更新时间:2023-09-26

我有一个网页,其中内容从json动态加载。现在我需要找到文本,如so2,co2,h2o页面加载后,必须为这些文本应用下标。这有可能吗?如果是,请告诉我实现它的更有效的方法。

例如:

var json = {chemA: " CO2的值为",chemB: " H2O的值为",chemC: " cue的值为"};

在上面的json我需要改变CO2,H2O和e在CTUe作为下标。如何做到这一点?

看一下这个JSfiddle,它显示了两种方法:

  1. 基于html的<sub>标签

  2. 基于纯javascript,用unicode中等效的下标替换匹配的数字:

http://jsfiddle.net/7gzbjxz3/

var json = { chemA: "CO2", chemB: "H2O" };
var jsonTxt = JSON.stringify(json).replace(/('d)+/g, function (x){
    return String.fromCharCode(8320 + parseInt(x));
});

选项2的优点是更便于移植,因为你实际上是在替换字符。也就是说,你可以将文本复制粘贴到记事本中,并且仍然可以在那里看到下标。

JSFiddle显示了这两种方法。不知道为什么这个神奇的数字是8320,当我期待它是2080…

所以你是根据JSON数据生成DOM元素,你得到。因此,在将其显示给DOM之前,您可以检查JSON数据是否包含so2,co2,h2o,如果是,然后将其替换为<sub>标签。

为例:

var text = 'CO2';
text.replace(/('d+)/g, "<sub>" + "$1" + "</sub>") ; 

这将返回如下内容:"CO2"。

根据您提供的JSON:

// Only working for integer right now
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is"};
$.each(json, function(index, value) {
    json[index] = value.replace(/('d+)/g, "<sub>" + "$1" + "</sub>");
});
console.log(json);

希望这将帮助!

为此,我将创建一个扩展Stringprototype函数,并将其命名为.toSub()。然后,当你从json中创建html时,调用.toSub()对任何可能包含下标文本的值:

// here is the main function
String.prototype.toSub = function() {
    var str=this;
    var subs = [
    		['CO2','CO<sub>2</sub>'],
    		['H2O','H<sub>2O</sub>'],
    		['CTUe','CO<sub>e</sub>'] // add more here as needed.
    ];
    for(var i=0;i<subs.length;i++){
         var chk = subs[i][0];
         var rep = subs[i][1];
   		 var pattern = new RegExp('^'+chk+'([ .?!])|( )'+chk+'([ .?!])|( )'+chk+'[ .?!]?$','ig');  // makes a regex like this: /^CO2([ .?!])|( )CO2([ .?!])|( )CO2[ .?!]?$/gi  using the surrent sub
         // the "empty" capture groups above may seem pointless but they are not
         // they allow you to capture the spaces easily so you dont have to deal with them some other way
         rep = '$2$4'+rep+'$1$3'; //  the $1 etc here are accessing the capture groups from the regex above 
    	 str = str.replace(pattern,rep); 
    }
  return str;
};
// below is just for the demo
var json = { chemA: "value of CO2 is", chemB: "value of H2O is" , chemC: "value in CTUe is", chemD: "CO2 is awesome", chemE: "I like H2O!", chemF: "what is H2O?", chemG: "I have H2O. Do you?"};
$.each(json, function(k, v) {
    $('#result').append('Key '+k+' = '+v.toSub()+'<br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

注意:

任何时候使用regex做类似的事情,都有可能无意中匹配和转换一些不需要的文本位。但是,这种方法比搜索和替换整个文档中的文本要少得多,因为它更有针对性。