最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Javascript - Change all numbers in a string to subscripts - Stack Overflow

programmeradmin6浏览0评论

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 bee subscripted?

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 bee subscripted?

Share Improve this question asked Jun 26, 2013 at 3:37 Rygh2014Rygh2014 1351 gold badge1 silver badge11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Use a simple regex replace as given below

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

Demo: Fiddle

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.

发布评论

评论列表(0)

  1. 暂无评论