Javascript-将字符串中的所有数字更改为下标 [英] Javascript - Change all numbers in a string to subscripts
本文介绍了Javascript-将字符串中的所有数字更改为下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个输入框,用户可以在其中输入化学式.我将他们的输入显示在一个表中,并在我的javascript文件中显示以下代码.
I have an input box in which the user inputs a chemical formula. I am displaying their input back to them in a table, with the following code in my javascript file.
document.getElementById("entered").innerHTML = userIn;
......其中,"userIn"是输入框的"id","entered"是表行中数据的ID.
...where "userIn" is the "id" of the input box, and "entered" is the id of the data in my table row.
现在,这是我的问题:
有什么办法可以将公式中的所有数字都更改为下标,但字母保持不变?那么,如果输入H2O2,只有2变成下标了?
Is there any way I can change all of the numbers in the formula to subscripts, but leaving the letters unchanged? So if H2O2 is entered, only the 2's become subscripted?
推荐答案
使用下面给出的简单正则表达式替换
Use a simple regex replace as given below
document.getElementById("entered").innerHTML = userIn.replace(/(\d+)/g, '<sub>$1</sub>');
演示:小提琴
这篇关于Javascript-将字符串中的所有数字更改为下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文