Regular Expression: match up to first colon in line

Discussion in 'Javascript' started by aliensite, Apr 10, 2005.

  1. aliensite

    aliensite Guest

    My code is too greedy, how can it be fixed?

    Here is my code:

    Desired output - First:,Second:,Third:
    <br>
    <script type="text/javascript">
    var regEx = /[^<>]*?:/g;
    var html = "<br>First:ratio<br />Second: 2:3<br>Third: size";
    var output = html.match(regEx);
    document.write(output);
    </script>

    Thanks for your help.
    Dave
     
    aliensite, Apr 10, 2005
    #1
    1. Advertisements

  2. So, in words, you want the parts between a ">" and the following ":".
    var regEx = />([^:]*:)/g;
    var html = "<br>First:ratio<br />Second: 2:3<br>Third: size";
    var output = [];
    while (match = regEx.exec(html)) {
    output.push(match[1]);
    }
    document.write(output);

    Good luck
    /L
     
    Lasse Reichstein Nielsen, Apr 10, 2005
    #2
    1. Advertisements

  3. aliensite

    aliensite Guest

    Thanks, I tried several expressions, but it seems only a loop works.
    Dave
     
    aliensite, Apr 11, 2005
    #3
  4. aliensite

    RobB Guest

    Possible alternative:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    </head>
    <body>
    <pre>
    Input -
    &amp;lt;br&amp;gt;First:ratio&amp;lt;br /&amp;gt;Second:
    2:3&amp;lt;br&amp;gt;Third: size

    Desired output -
    First:,Second:,Third:

    Actual output -
    <script type="text/javascript">
    var re = /<[^>]+>([^:]*):[^<]*/g;
    var html = '<br>First:ratio<br />Second: 2:3<br>Third: size';
    var output = html.replace(re, '$1:,').replace(/,$/, '');
    document.writeln(output);
    </script>
    </pre>
    </body>
    </html>
     
    RobB, Apr 11, 2005
    #4
  5. aliensite

    aliensite Guest


    Nice :)
     
    aliensite, Apr 13, 2005
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.