MB34 MB34 - 5 months ago 21
Javascript Question

Regex replace total string

I have and XML file with items that contain this string:

<field name="itemid">xx</field>


Where
xx
= a number from 50 to 250.

I need to remove the entire string from the whole file.

How would I do this with a Regex
replace
?

Answer

you can use this:

str = str.replace(/<.*>/g,'');

See an example for match here

var str = "<field name='itemid'>xx</field>";
str = str.replace(/<.*>/g, 'replaced');
console.log(str)

Explanation:

  • < matches the character < literally
  • .* matches any character (except newline)
    • Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
  • > matches the character > literally
  • g modifier: global. All matches (don't return on first match)

If you want to be more restrictive you can do this:

str = str.replace(/\<field name\=\"\w*\"\>\d*\<\/field\>/g, '');

See an example for match here

var str = '<field name="test">200</field>';
str = str.replace(/\<field name\=\"\w*\"\>\d*\<\/field\>/g, 'replaced');
console.log(str)

Explanation:

  • \< matches the character < literally field name matches the characters field name literally (case sensitive)
  • \= matches the character = literally
  • \" matches the character " literally
  • \w* match any word character [a-zA-Z0-9_]
    • Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
  • \" matches the character " literally -\> matches the character > literally
  • \d* match a digit [0-9] - Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
  • \< matches the character < literally
  • \/ matches the character / literally field matches the characters field literally (case sensitive)
  • \> matches the character > literally
  • g modifier: global. All matches (don't return on first match)
Comments