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?

4
  • It looks like you are trying to parse HTML with regex. You could just parse the string into DOM and go from there.. Commented May 15, 2012 at 15:37
  • Regular expressions are complicated enough on their own. If every language had different writing it would be hell! Commented May 15, 2012 at 15:37
  • Just have a look at regular-expressions.info/javascript.html. Commented May 15, 2012 at 15:41
  • 1
    Also have a look at stackoverflow.com/a/1732454/851498 . This is one of the most upvoted answers on StackOverflow. Commented May 15, 2012 at 15:44

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

So yeah that means... It's not good idea to use regular expression when I need to parse html right?
Exactly :) HTML cannot be parsed with a regex correctly, see the link for examples.
@SoftwareGuruji nope especially in browsers you can easily convert a string into queryable dom. var root = document.createElement("div"); root.innerHTML = "<a id='pres'></a>"; console.log( root.firstChild.id)
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.

1 Comment

@thagorn Just noticed myself :)
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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.