str.replace

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Brian

    str.replace

    I want to use regxp to check that a form input contains at least 1
    non-space charcter. I'd like to only run this if the browser supports
    it. For DOM stuff, I'd use

    if (documentGetEle mentById) {}

    Is there an object/feature detection I can use to check for regxp string
    manipulation support?

    --
    Brian (remove ".invalid" to email me)

  • Michael Winter

    #2
    Re: str.replace

    On Sun, 15 Aug 2004 11:40:30 -0400, Brian
    <usenet3@juliet remblay.com.inv alid> wrote:
    [color=blue]
    > I want to use regxp to check that a form input contains at least 1
    > non-space charcter. I'd like to only run this if the browsersupports it.
    > For DOM stuff, I'd use
    >
    > if (documentGetEle mentById) {}[/color]

    You mean

    if(document.get ElementById) ...
    [color=blue]
    > Is there an object/feature detection I can use to check for regxpstring
    > manipulation support?[/color]

    There's no need. Regular expressions have existed in JavaScript since v1.2
    (NN4). The only thing you do need to test is that more recent additions to
    the available constructs (lookahead matches and the like) are supported.

    Hope that helps,
    Mike

    --
    Michael Winter
    Replace ".invalid" with ".uk" to reply by e-mail

    Comment

    • Richard Cornford

      #3
      Re: str.replace

      Brian wrote:[color=blue]
      > I want to use regxp to check that a form input contains at least 1
      > non-space charcter. I'd like to only run this if the browser supports
      > it. For DOM stuff, I'd use
      >
      > if (documentGetEle mentById) {}[/color]

      Assuming you mean:-

      if (document.getEl ementById) {}

      - it would be reckless to infer any level of DOM support (especially
      dynamic DOM support) form that test. The only valid deduction available
      form that test is that the browser supports - document.getEle mentById -
      (useful to know if you intend using it but not the whole picture).

      [color=blue]
      > Is there an object/feature detection I can use to check for
      > regxp string manipulation support?[/color]

      As your subjuect implies an interest in the string - replace - method:-

      if(
      (typeof String == 'function') &&
      (String.prototy pe) &&
      (String.prototy pe.replace)
      ){
      ... // String.prototyp e.replace is available.
      }

      Though realistically you can expect to have a - replace - method
      available on all browser javascript implementations currently in use
      (still, no harm in making sure).

      The capabilities of String.prototyp e.replace might be additionally
      tested with:-

      <URL:
      http://jibbering.com/faq/faq_notes/n...html#bdReplace >

      Unfortunately jibbering.com appears to be unavailable at present so this
      is the code used in that page:-

      /* The original string is the one letter string literal "a". The
      Regular Expression /a/ identifies that entire string, so it is the
      entire original string that will be replaced. The second argument is
      the function expression - function(){retu rn ''';} -, so the entire
      original string will be replaced with an empty string if the
      function expression is executed. If it is instead type-converted
      into a string that string will not be an empty string. The NOT (!)
      operation type-converts its operand to boolean and then inverts it
      so the results of the test is boolean true if function references
      are supported in the second argument for the - replace - method, and
      false when not supported:
      */
      if(!('a'.replac e(/a/, (function(){ret urn '';})))){
      ... //function references OK.
      }else{
      ... //no function references with replace.
      }

      If you want different, or more specific, regular expression testing then
      the nature of the real problem defines the appropriate test and you have
      not yet elucidated the real circumstances/problem.

      Richard.


      Comment

      • Jim Ley

        #4
        Re: str.replace

        On Sun, 15 Aug 2004 17:30:02 +0100, "Richard Cornford"
        <Richard@litote s.demon.co.uk> wrote:
        [color=blue]
        >Brian wrote:
        ><URL:
        >http://jibbering.com/faq/faq_notes/n...html#bdReplace >
        >
        >Unfortunatel y jibbering.com appears to be unavailable at present so this
        >is the code used in that page:-[/color]

        I won't go into the details why it's deaf, but I'm not happy a
        bunny... hopefully back sometime in the afternoon of monday UK time.

        Apologies everyone!

        Jim.

        Comment

        • Brian

          #5
          Re: str.replace

          Michael Winter wrote:
          [color=blue]
          > Brian wrote:
          >[color=green]
          >> Is there an object/feature detection I can use to check for
          >> regxpstring manipulation support?[/color]
          >
          > There's no need. Regular expressions have existed in JavaScript since
          > v1.2 (NN4).[/color]

          I'll defer to you on this, though it does make me nervous. I hate the
          idea of unleasing any js without some sort of check first.
          [color=blue]
          > The only thing you do need to test is that more recent additions to
          > the available constructs (lookahead matches and the like) are
          > supported.[/color]

          I'd be using something fairly simple (I think!), for onSubmit:

          strTrimmed = str.replace(/\s+/g, '');
          if (strTrimmed == "") {
          // user tried to submit empty search query --
          // insert error message in page or alert error
          return false;
          }

          --
          Brian (remove ".invalid" to email me)

          Comment

          • Brian

            #6
            Re: str.replace

            Richard Cornford wrote:
            [color=blue]
            > Brian wrote:
            >[color=green]
            >> I want to use regxp to check that a form input contains at least 1
            >> non-space charcter. I'd like to only run this if the browser
            >> supports it. For DOM stuff, I'd use
            >>
            >> if (documentGetEle mentById) {}[/color]
            >
            > Assuming you mean:-
            >
            > if (document.getEl ementById) {}[/color]

            I did; apologies for not editing more carefully.
            [color=blue]
            > - it would be reckless to infer any level of DOM support (especially
            > dynamic DOM support) form that test.[/color]

            In the interest of keeping my post short, I erred on the side of
            concise. When I'm doing anything dynamic with a document, I try to find
            each method I'll use and test for that, e.g.,

            if (document.getEl ementsByTagName && document.create Element &&
            document.create TextNode) {}

            Since this Usenet, I should have been a little more thorough, if only to
            avoid misleading others.
            [color=blue][color=green]
            >> Is there an object/feature detection I can use to check for regxp
            >> string manipulation support?[/color]
            >
            > if(
            > (typeof String == 'function') &&
            > (String.prototy pe) &&
            > (String.prototy pe.replace)
            > ){
            > ... // String.prototyp e.replace is available.
            > }[/color]


            Thanks for that. I'm still learning, so it'll take a bit of time for me
            to work through it. I've seen "typeof" comparisons, but I'm not sure
            what they mean.

            Aside: one of the challenges with learning JavaScript is that there
            seems to be more bad advice on the web than good, so a simple Google
            search does not always help.
            [color=blue]
            > Though realistically you can expect to have a - replace - method
            > available on all browser javascript implementations currently in use
            > (still, no harm in making sure).[/color]

            ISTR that older browsers handle js errors rather crudely, but I cannot
            be sure. Nor can I say whether it makes sense to fuss about IE 3.x or NN
            3.x.
            [color=blue]
            > Unfortunately jibbering.com appears to be unavailable at present[/color]

            I noticed that during research for this question; I was in fact trying
            to read the faq.
            [color=blue]
            > /* The original string is the one letter string literal "a". The
            > Regular Expression /a/ identifies that entire string, so it is the
            > entire original string that will be replaced. The second argument is
            > the function expression - function(){retu rn ''';} -[/color]
            [snip]

            Yikes, I'm afraid that's a bit out of my league, but I've copied your
            entire message for future reference.
            [color=blue]
            > If you want different, or more specific, regular expression testing
            > then the nature of the real problem defines the appropriate test and
            > you have not yet elucidated the real circumstances/problem.[/color]

            I read this article yesterday:



            Point 3 suggested using js to help users avoid sending an empty string
            to a site search. I thought that was a good idea, and pretty easy to do,
            so I started writing a script. Then I thought that it would be nice to
            also check for a string of only whitespace as well as an empty string.

            In short: I have a site search form. Onsubmit, I want to strip all white
            space from an text input field, then see if there are any characters
            left. If there are not, I want to tell the user about the problem and
            return false.

            --
            Brian (remove ".invalid" to email me)

            Comment

            • Brian

              #7
              Re: str.replace

              Brian wrote:
              [color=blue]
              > I have a site search form. Onsubmit, I want to strip all white
              > space from an text input field, then see if there are any characters
              > left.[/color]

              It just occurred to me that I should be able to simply look for a
              non-whitespace character:

              s = /.*\S.*/;
              if (!s.test(str)) {
              // warn user and return false
              }

              Have I missed something obvious?

              --
              Brian (remove ".invalid" to email me)

              Comment

              • Lasse Reichstein Nielsen

                #8
                Re: str.replace

                Brian <usenet3@juliet remblay.com.inv alid> writes:
                [color=blue]
                > It just occurred to me that I should be able to simply look for a
                > non-whitespace character:
                >
                > s = /.*\S.*/;
                > if (!s.test(str)) {[/color]
                ....[color=blue]
                > Have I missed something obvious?[/color]
                If you don't anchor the RegExp (with "^" and "$") then it matches
                anywhere in the string, so ".*" isn't necessary:

                var s = /\S/;

                Otherwise fine.
                /L
                --
                Lasse Reichstein Nielsen - lrn@hotpop.com
                DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                'Faith without judgement merely degrades the spirit divine.'

                Comment

                • Michael Winter

                  #9
                  Re: str.replace

                  On Sun, 15 Aug 2004 15:18:59 -0400, Brian
                  <usenet3@juliet remblay.com.inv alid> wrote:

                  [regexp support is common]
                  [color=blue]
                  > I'll defer to you on this, though it does make me nervous. I hatethe
                  > idea of unleasing any js without some sort of check first.[/color]

                  I think it would be pretty reckless for any browser to ignore support for
                  regular expressions. It's also part of the core language, so conforming
                  implementations must provide them.

                  If you wanted to check for the RegExp host object, you could try:

                  /* Get a reference to the global object,
                  * parent to built-in objects. */
                  var global = this;

                  if('function' == typeof global['RegExp'] &&
                  RegExp.prototyp e &&
                  RegExp.<name of function> )
                  {
                  // <name of function> supported
                  }

                  Yes, this is somewhat nabbed from Richard's post, however, I think that
                  it's prudent to not access the RegExp identifier directly in case it's not
                  provided (however unlikely that might be). If accessed directly by name:

                  if(RegExp) {

                  but not present, it will cause an error. If accessed as a property of an
                  object, it will simply evaluate to undefined.

                  With regard to using typeof, everything is represented by some form of
                  object. The various basic types are: undefined, null, boolean, number,
                  string, and object. When the typeof operator is used with one of these
                  types, it evaluates to a string that contains one of the following values:

                  Type Result
                  --------------------------------
                  Undefined "undefined"
                  Null "object"
                  Boolean "boolean"
                  Number "number"
                  String "string"
                  Object (native and "object"
                  doesn't implement
                  [[Call]])
                  Object (native and "function"
                  implements [[Call]])
                  Object (host) Implementation-dependent

                  This could be used for various purposes:

                  - Checking that a property is implemented

                  Unlike methods, you can't just use

                  if(object.prope rty) {
                  // property implemented - doesn't work!

                  because the property could be one of many values that evaluate to false.
                  Instead, you use the typeof operator to distinguish the results:

                  if('undefined' != typeof object.property ) {
                  // property implemented

                  - Overloading methods

                  In other languages, you can specify methods with the same name, but a
                  different signature; different arguments types. As JavaScript is
                  loosely-typed, this isn't possible in the same way. However, you can use
                  typeof to effect the same behaviour.

                  function useObject(o) {
                  /* If o is a string, use some method to obtain an
                  * appropriate object reference. */
                  if('string' == typeof o) {
                  o = getRef(o);
                  }
                  /* Check that o is now an object
                  * and that it's not null. */
                  if(o && 'object' == typeof o) {

                  There are bound to be other possibilities, but I lost my train of thought
                  after watching TV. :)

                  [snip]
                  [color=blue]
                  > strTrimmed = str.replace(/\s+/g, '');
                  > if (strTrimmed == "") {
                  > // user tried to submit empty search query --
                  > // insert error message in page or alert error
                  > return false;
                  > }[/color]

                  Simpler still would be:

                  if(!/\S+/.test(str)) {
                  return false;
                  }

                  The regular expression, \S+, matches any string that contains one or more
                  non-whitespace characters.

                  Hope that helps,
                  Mike

                  --
                  Michael Winter
                  Replace ".invalid" with ".uk" to reply by e-mail

                  Comment

                  • Brian

                    #10
                    Re: str.replace

                    Lasse Reichstein Nielsen wrote:
                    [color=blue]
                    > Brian writes:
                    >[color=green]
                    >> s = /.*\S.*/;[/color]
                    >
                    >
                    > If you don't anchor the RegExp (with "^" and "$") then it matches
                    > anywhere in the string, so ".*" isn't necessary:
                    >
                    > var s = /\S/;[/color]

                    Even better! Thanks for your time.

                    --
                    Brian (remove ".invalid" to email me)

                    Comment

                    • Richard Cornford

                      #11
                      Re: str.replace

                      Michael Winter wrote:
                      <snip>[color=blue]
                      > Yes, this is somewhat nabbed from Richard's post, however, I
                      > think that it's prudent to not access the RegExp identifier
                      > directly in case it's not provided (however unlikely that
                      > might be). If accessed directly by name:
                      >
                      > if(RegExp) {
                      >
                      > but not present, it will cause an error. If accessed as a
                      > property of an object, it will simply evaluate to undefined.[/color]
                      <snip>

                      In a type-converting test an unqualified identifier that is not resolved
                      as a named property of some object on the scope chain will result in an
                      error. However, - typeof - has an extra safety measure in its specified
                      algorithm:-

                      <quote cite="ECMA 262 3rd edition">
                      11.4.3 The typeof Operator

                      The production UnaryExpression : typeof UnaryExpression is evaluated as
                      follows:

                      1. Evaluate UnaryExpression .
                      2. If Type(Result(1)) is not Reference, go to step 4.
                      3. If GetBase(Result( 1)) is null, return "undefined" .
                      4. Call GetValue(Result (1)).
                      5. Return a string determined by type(Result(4)) according
                      to the following table:
                      [ ... table as quoted in previous post ]
                      </quote>

                      Identifier resolution (ECMA 262 3rd edition section 10.1.4) always
                      returns an Reference type, with an unresolved identifier returning a
                      Reference type with a null base object, so step 3 in the typeof
                      algorithm safely returns "undefined" .

                      Richard.


                      Comment

                      • Michael Winter

                        #12
                        [thanks] Re: str.replace

                        On Sun, 15 Aug 2004 22:46:56 +0100, Richard Cornford
                        <Richard@litote s.demon.co.uk> wrote:

                        [snip]
                        [color=blue]
                        > In a type-converting test an unqualified identifier that is not resolved
                        > as a named property of some object on the scope chain will result in an
                        > error. However, - typeof - has an extra safety measure in its specified
                        > algorithm:-[/color]

                        Thank you for that. I think it's fair to say I had no idea, despite
                        staring straight at what you quoted. I wouldn't have reached the same
                        conclusion anyway: my ability to comprehend ECMA-262 has drastically
                        improved, but I still know little of the low-level mechanics of the
                        language.

                        [snip]

                        Mike

                        --
                        Michael Winter
                        Replace ".invalid" with ".uk" to reply by e-mail

                        Comment

                        • Brian

                          #13
                          Re: str.replace

                          Michael Winter wrote:
                          [color=blue]
                          > I think it would be pretty reckless for any browser to ignore support
                          > for regular expressions. It's also part of the core language, so
                          > conforming implementations must provide them.[/color]

                          Good to know. My nervousness comes from a lack of experience in js, and
                          warnings from knowledeable hackers about object detection.
                          [color=blue]
                          > If you wanted to check for the RegExp host object, you could try:[/color]

                          [lots of useful info snipped]
                          [color=blue]
                          > Hope that helps[/color]

                          Quite a bit. Thanks to everyone who posted in this thread. I'm much
                          closer to my goal than I was 2 days ago. :-)

                          --
                          Brian (remove ".invalid" to email me)

                          Comment

                          Working...