0

Task: Replace all <h[n]> tags with <h2>.

My Code:

const helloWorld = '<h1>Hello world</h1>';
const values = helloWorld.match(/<h[0-9]>[\s\S]*<\/h[0-9]>/g).map((val) => {
  return val.replace(/<h[0-9]>/g, '').replace(/<\/h[0-9]/g, '');
});

for(let i = 0; i < values.length; i++){
  helloWorld.replace(/<h[0-9]>[\s\S]*<\/h[0-9]>/g, '<h2>'+values[i]+'</h2>');
}
console.log(helloWorld);

Expected:

<h2>Hello world</h2>

Output:

<h1>Hello world</h1>

ICanKindOfCode
  • 1,000
  • 1
  • 11
  • 32

3 Answers3

1

The replace() method returns a new string with some or all matches of a pattern replaced by a replacement.

Javascript is a functional language thus its recommended to treat all variables as immuteable.

So for the change to take place you would want to assign the output of the replace function to your modified variable

helloWorld = helloWorld.replace(/<h[0-9]>[\s\S]*<\/h[0-9]>/g, '<h2>'+values[i]+'</h2>');
Idan Beker
  • 353
  • 2
  • 9
1

You can use this regex expression: /(<\/?h)([0-6])/ with global and ignore case flags.

Answering your comments:

It's just replacing the string with the new value. With replace method you can use $n as a parameter. In my example I added two groups, if we have a match, i concatenate the first match parameter (</?>) with "2".

You can read more about "replace" here (Section: "Specifying a string as a parameter"): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

The array + map method is just to test/exemplify more than 1 option.

You can also use without RegExp.

yourString.replace(/(<\/?h)([0-6])/ig, "$12"); //same result

Sample:

const reg = new RegExp(/(<\/?h)([0-6])/, 'ig');

const values = [
  '<h1>Hello world</h1>',
  '<h2 class="something">Hello world</h2>',
  '<h3 id="a">Hello world</h3>',
  '<h2>Hello world</h2>'
]

const newValues = values.map(item => item.replace(reg, "$12"))

console.log(newValues);
Eduardo Stuart
  • 2,869
  • 18
  • 22
0

According to the documentation, string.replace() returns the modified value as the result of the function call. It does not mutate the string.

so

helloWorld.replace(/<h[0-9]>[\s\S]*<\/h[0-9]>/g, '<h2>'+values[i]+'</h2>');

should be

helloWorld = helloWorld.replace(/<h[0-9]>[\s\S]*<\/h[0-9]>/g, '<h2>'+values[i]+'</h2>');
Sam Axe
  • 33,313
  • 9
  • 55
  • 89