itinance itinance - 3 months ago 9
HTML Question

Javascript: transform content between Html-Tags to upperCacse

I want to uppercase the contents of specific HTML-Tags with plain javascript in a React-Native application (no jQuery available, "document" is also not supported):

Let's say, there is the following HTML-Text:

<p>This is an <mytag>simple Example</mytag></p>

The content of the Tag < mytag > shall be transformed to uppercase:

<p>This is an <mytag>SIMPLE EXAMPLE</mytag></p>

I tried this one:

let regEx = storyText.match(/<mytag>(.*?)<\/mytag>/g)
if(regEx) storyText ={
return val.toUpperCase();

But the map-function returns only the matched content instead of the whole string variable with the transformed part of < mytag >.

Also, the match-method will return null, if the tag wasn't found. So a fluent programming style like "storyText.match().doSomethign" isnt possible.

Since there are more tags to transform, an approach where i can pass variables to the regex-pattern would be appreciated.

Any hints about that?

(I know that one can style those transformations with CSS-text-transform, but this html-text above isn't supposed to be displayed in a Webbrowser.
This code is used in a React-Native-App with the "react-native-html-view"-Plugin which doesn't support text-transform out of the box.)


Since it seems that document and DOM manipulation (e.g., i.e., through jQuery and native JS document functions) are off limits, I guess you do have to use regex.

Then why not just create a function that does a job like the above: looping through each tag and replacing it via regex?

var storyText = "your HTML in a string";
function tagsToUppercase(tags) {
  for(tag in tags) {
    let regex = new RegExp("(<" + tags[tag] + ">)([^<]+)(<\/" + tags[tag] + ">)", "g");
    storyText = storyText.replace(regex, function(match, g1, g2, g3) {
      return g1 + g2.toUpperCase() + g3;

// uppercase all <div>, <p>, <span> for example
tagsToUppercase(["div", "p", "span"]);

See it working on JSFiddle.