1

I have this HTML string.

some text <pre>01     02     bb      67
02     g2     cc      67<br />
<b>03     32     dd      67</b>
04     q2     ee      67</pre> some text

I need a javascript regex to get the text/html inside the PRE tag and manipulate it. It's pure text, no DOM manipulation here.

P.s. Sorry for my english.

SergeS
  • 11,533
  • 3
  • 29
  • 35
EderBaum
  • 993
  • 13
  • 16
  • If there is no DOM , there is no dhtml – SergeS Feb 17 '12 at 19:00
  • 1
    the `
    ` cannot hold, it is too late...
    – jAndy Feb 17 '12 at 19:00
  • 1
    I don't care how simple your HTML string is, [you can't parse HTML with regex](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). – James M Feb 17 '12 at 19:00
  • If you want a RegEx solution, you have provide very solid patterns. If a piece of text is always supplied in the same format, then RegExps can be used. Otherwise, you might consider using DOM manipulation instead of a RegExp. – Rob W Feb 17 '12 at 19:03
  • What specific manipulation do you want to do on it? We can't help with the regex without knowing what you're trying to accomplish. – jfriend00 Feb 17 '12 at 19:07

1 Answers1

1

Here's how you can get the contents of the pre tag using javascript's match() method:

var preContents = myHTMLString.match(/<pre>.*?<\/pre>/ims).substr(5, -6);

That searches for a pre tag, the contents, and the closing pre tag, then removes the opening and closing pre tags, and stores the contents in the preContents variable.

To manipulate it, you could then edit preContents to suit your needs and use javascript's replace() method to change the contents:

myHTMLString = myHTMLString.replace(/<pre>.*?<\/pre>/ims, '<pre>' + manipulatedPreContents + '</pre>');
BenjaminRH
  • 11,974
  • 7
  • 49
  • 76
  • Its a string, and i need replace the inner text with a lot of manipulation. Something like this -> str.replace(/
    .*?<\/pre>/ig, function($1){   
        return $1.replace(/
    /g, '\r\n'); });
    – EderBaum Feb 17 '12 at 19:12
  • If you stick `(` `)`s around `.*?` then it creates a group for the match. Meaning you don't need to remove the `pre` tags with `substr`. – Davey Jul 19 '22 at 09:01