Javascript - Change all numbers in a string to subscripts

心不动则不痛 提交于 2020-11-28 02:02:04

问题


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;

...where "userIn" is the "id" of the input box, and "entered" is the id of the data in my table row.

Now, here's my question:

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?


回答1:


Use a simple regex replace as given below

document.getElementById("entered").innerHTML = userIn.replace(/(\d+)/g, '<sub>$1</sub>');

Demo: Fiddle




回答2:


You can use a regex to surround all of the digits in userIn with <sub></sub> tags. The following should work:

userIn.replace(/(\d+)/g, "<sub>$1</sub>");

The + in the regex will group a string of consecutive digits together and the tailing g in the regex says to replace all the strings of digits instead of just replacing the first string of digits in userIn.



来源:https://stackoverflow.com/questions/17311116/javascript-change-all-numbers-in-a-string-to-subscripts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!