0

Initial have:

var e.name = 'Mg2(OH)3';

Need to have:

var sub = '<p>Mg<span class="sub">2</span>(OH)<span class="sub">3</span</p>';

Need to add before and after number the span. How to do that with jQuery or on native javascript?

1
  • 4
    nothing to do with jquery. that's just string manipulation. Commented May 25, 2015 at 16:22

2 Answers 2

2

Use .replace method, no jQuery needed.

var str = 'Mg2(OH)3';
str = '<p>' + str.replace(/(\d+)/g, '<span class="sub">$1</span>') + '</p>';
console.log(str); // returns: <p>Mg<span class="sub">2</span>(OH)<span class="sub">3</span></p>
Sign up to request clarification or add additional context in comments.

Comments

0

Also adding the enclosing paragraph tags:

var e = {};

e.name = 'Mg2(OH)3';

var sub = '<p>Mg<span class="sub">2</span>(OH)<span class="sub">3</span></p>';

e.name = '<p>' + e.name.replace(/(\d+)/g, '<span class="sub">$1</span>') + '</p>';

console.log(sub);

console.log(e.name);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.