0

I have an regular expression built in Java.

String expr = "<a.*?id=\"(pres.*?)\".*?>Discharge.*?Medications:</a>";

I want to use same regular expression in Javascript. Will it be different or same?

Ketan Bhavsar
  • 5,338
  • 9
  • 38
  • 69

4 Answers4

5

I suggest you don't do it.

Why? I will just point you out to one of the most upvoted answer on StackOverflow: https://stackoverflow.com/a/1732454/851498

In javascript, you'd better use the DOM than a regex to parse HTML.

Example:

var a = document.querySelectorAll('a');
for ( var i = 0, len = a.length; i < len; i++ ) {
    // If the id starts with "pres"
    if ( a[ i ].id.substr( 0, 3 ) === 'pres' ) {
        // check a[ i ].textContent
    }
}

Or if you're using jQuery:

$('a').each( function() {
    if ( this.id.substr( 0, 3 ) === 'pres' ) {
        // check $( this ).text()
    }
} );

I didn't code the last part, but you get the idea. Using a regex on $( this ).text() would be fine, it's not HTML.

Community
  • 1
  • 1
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
  • So yeah that means... It's not good idea to use regular expression when I need to parse html right? – Ketan Bhavsar May 15 '12 at 15:54
  • Exactly :) HTML **cannot** be parsed with a regex correctly, see the link for examples. – Florian Margaine May 15 '12 at 15:55
  • @SoftwareGuruji nope especially in browsers you can easily convert a string into queryable dom. `var root = document.createElement("div"); root.innerHTML = ""; console.log( root.firstChild.id)` – Esailija May 15 '12 at 15:56
2

Not much different. Regex's in JavaScript are between /'s. So it would look like this:

var expr = /<a.*?id=\"(pres.*?)\".*?>Discharge.*?Medications:</a>/;

Edit, wrong slash. Oops.

Jivings
  • 22,834
  • 6
  • 60
  • 101
2

Alternatively, you can do:

var expr = new RegExp("<a.*?id=\"(pres.*?)\".*?>Discharge.*?Medications:</a>");

For more details on RegExp in JavaScript see the MDN docs: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

mikeycgto
  • 3,368
  • 3
  • 36
  • 47
1

It will be the same. All the mainstream regular expression engines support the same basic syntax for regular expressions. Some add their own features on top, but your example isn't doing anything outlandish.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399