replace string literal

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

    replace string literal

    How would one make the ECMA-262 String.replace method work with a
    string literal?

    For example, if my string was "HELLO[WORLD]" how would I make it work
    in this instance.

    Please note my square brackets are not regular expression syntax.

    Thanks,

    Gary

  • Ian Collins

    #2
    Re: replace string literal

    gary wrote:[color=blue]
    > How would one make the ECMA-262 String.replace method work with a
    > string literal?
    >
    > For example, if my string was "HELLO[WORLD]" how would I make it work
    > in this instance.
    >
    > Please note my square brackets are not regular expression syntax.
    >[/color]
    Try

    alert("hello".r eplace(/ll/i, 'jj') );

    String literals are objects in JavaScript, unlike C.

    --
    Ian Collins.

    Comment

    • gary

      #3
      Re: replace string literal

      Thank you very much for the reply, however, this does not solve my
      problem.

      For example

      var h = "he[ll]o";
      var regx = new RegExp ( h , 'i' );
      alert(h.replace (regx, 'jj') );

      Displays "he[ll]o" and not "he[jj]o" which is what I want.

      Gary



      Ian Collins wrote:[color=blue]
      > gary wrote:[color=green]
      > > How would one make the ECMA-262 String.replace method work with a
      > > string literal?
      > >
      > > For example, if my string was "HELLO[WORLD]" how would I make it work
      > > in this instance.
      > >
      > > Please note my square brackets are not regular expression syntax.
      > >[/color]
      > Try
      >
      > alert("hello".r eplace(/ll/i, 'jj') );
      >
      > String literals are objects in JavaScript, unlike C.
      >
      > --
      > Ian Collins.[/color]

      Comment

      • Ian Collins

        #4
        Re: replace string literal

        gary wrote:

        Please don't top post!
        [color=blue]
        > Ian Collins wrote:
        >[color=green]
        >>gary wrote:
        >>[color=darkred]
        >>>How would one make the ECMA-262 String.replace method work with a
        >>>string literal?
        >>>
        >>>For example, if my string was "HELLO[WORLD]" how would I make it work
        >>>in this instance.
        >>>
        >>>Please note my square brackets are not regular expression syntax.
        >>>[/color]
        >>
        >>Try
        >>
        >>alert("hello" .replace(/ll/i, 'jj') );
        >>
        >>String literals are objects in JavaScript, unlike C.
        >>[/color]
        > Thank you very much for the reply, however, this does not solve my
        > problem.
        >
        > For example
        >
        > var h = "he[ll]o";
        > var regx = new RegExp ( h , 'i' );
        > alert(h.replace (regx, 'jj') );
        >
        > Displays "he[ll]o" and not "he[jj]o" which is what I want.
        >[/color]
        Which is exactly what my example does. What are you attempting to do?

        --
        Ian Collins.

        Comment

        • Richard Cornford

          #5
          Re: replace string literal

          Ian Collins wrote:[color=blue]
          > gary wrote:[color=green]
          >> How would one make the ECMA-262 String.replace method work
          >> with a string literal?[/color][/color]
          <snip>[color=blue]
          > Try
          >
          > alert("hello".r eplace(/ll/i, 'jj') );
          >
          > String literals are objects in JavaScript, unlike C.[/color]

          No they are not. String primitive and string objects are distinct in
          javascript, and string literals define string primitives.

          The above works because the dot operator implicitly type-converts its
          left hand side operand into an object, so the above is implicitly
          equivalent to:-

          alert((new String("hello") ).replace(/ll/i, 'jj') );

          Richard.


          Comment

          • Csaba  Gabor

            #6
            Re: replace string literal

            Richard Cornford wrote:[color=blue]
            > Ian Collins wrote:[color=green]
            > > alert("hello".r eplace(/ll/i, 'jj') );
            > >
            > > String literals are objects in JavaScript, unlike C.[/color]
            >
            > No they are not. String primitive and string objects are distinct in
            > javascript, and string literals define string primitives.
            >
            > The above works because the dot operator implicitly type-converts its
            > left hand side operand into an object, so the above is implicitly
            > equivalent to:-
            >
            > alert((new String("hello") ).replace(/ll/i, 'jj') );[/color]

            But perhaps you could clear something up for me. If I pass a string
            object to a function (that may return an altered string), a reference
            should be passed. So it would be more efficient, in general, to pass a
            string object and have the function change the underlying string rather
            than having to return the string, since returning means that the string
            must be copied when there are no changes. My question is, how does one
            change the string of the string object without bothering the reference?
            I could always wrap the string in an array, but that doesn't seem like
            it's in the right spirit.

            Csaba Gabor from Vienna

            In this non working example, I'd like the line in the function to
            change the contents of the string object instead of changing the object
            itself (which, as a result, won't be reflected in the caller).


            var oStr = new String("example string")
            function changeoStr (oStr) {
            // possibly oStr.__parent__ or oStr.__proto__ could help?
            // doesn't work. I'd just like the underlying string changed
            oStr = "new string";
            }
            changeoStr(oStr );
            alert (oStr); // I'd like the alert to show "new string"

            Comment

            • Richard Cornford

              #7
              Re: replace string literal

              Csaba Gabor wrote:[color=blue]
              > Richard Cornford wrote:[/color]
              <snip>[color=blue][color=green]
              >> ... . String primitive and string objects are distinct in
              >> javascript, and string literals define string primitives.[/color][/color]
              <snip>[color=blue]
              > ... . My question is, how does one change the string of the string
              > object without bothering the reference?[/color]
              <snip>

              Javascript does not have any means of changing the internal value of a
              String object.

              Richard.

              Comment

              • Ian Collins

                #8
                Re: replace string literal

                Richard Cornford wrote:[color=blue]
                > Ian Collins wrote:
                >[color=green]
                >>gary wrote:
                >>[color=darkred]
                >>>How would one make the ECMA-262 String.replace method work
                >>>with a string literal?[/color][/color]
                >
                > <snip>
                >[color=green]
                >>Try
                >>
                >>alert("hello" .replace(/ll/i, 'jj') );
                >>
                >>String literals are objects in JavaScript, unlike C.[/color]
                >
                >
                > No they are not. String primitive and string objects are distinct in
                > javascript, and string literals define string primitives.
                >[/color]
                OK, thanks for pointing that out.

                --
                Ian Collins.

                Comment

                • Csaba  Gabor

                  #9
                  Re: replace string literal

                  Richard Cornford wrote:[color=blue]
                  > Csaba Gabor wrote:[color=green]
                  > > Richard Cornford wrote:[/color]
                  > <snip>[color=green][color=darkred]
                  > >> ... . String primitive and string objects are distinct in
                  > >> javascript, and string literals define string primitives.[/color][/color]
                  > <snip>[color=green]
                  > > ... . My question is, how does one change the string of the string
                  > > object without bothering the reference?[/color]
                  > <snip>
                  >
                  > Javascript does not have any means of changing the internal value of a
                  > String object.[/color]

                  Thanks, I was afraid you might say something like that.
                  Well, if I can't unwrap the string object to get to the string, at
                  least I can wrap up the string in my own object to pretend that it's a
                  string object. Thus, I have a cleaner way to pass the string by
                  reference than wrapping it in an array. That is to say, other than a
                  distinct way to create it and a new in place replacement function
                  (.selfReplace), it appears to old code as a normal string.

                  I tried to modify the String object itself, similarly to the below (by
                  giving it a self value, to override any original value), but I didn't
                  get it working (yet?).

                  Csaba


                  function oString(str) {
                  this.__proto__ = new String(str);
                  this.toString = function() {return this.__proto__. toString(); };
                  this.valueOf = function() {return this.__proto__. valueOf(); };
                  this.selfReplac e = function(needle RegExp, strReplacement) {
                  this.__proto__ = new String(this.rep lace(needleRegE xp,
                  strReplacement) ); } }
                  function changeStr (oStr, newStr) { oStr.selfReplac e(/.*/, newStr); }

                  var oStr = new oString("my string"); alert("length: " + oStr.length);
                  oStr.selfReplac e (/str/,"th"); alert("replaced string: " + oStr);
                  changeStr(oStr, "something new"); alert("changed string: " + oStr);

                  Comment

                  • Dr John Stockton

                    #10
                    Re: replace string literal

                    JRS: In article <1149556449.532 678.93950@f6g20 00cwb.googlegro ups.com>,
                    dated Mon, 5 Jun 2006 18:14:09 remote, seen in
                    news:comp.lang. javascript, gary <gbrewer@gmail. com> posted :[color=blue]
                    >How would one make the ECMA-262 String.replace method work with a
                    >string literal?
                    >
                    >For example, if my string was "HELLO[WORLD]" how would I make it work
                    >in this instance.
                    >
                    >Please note my square brackets are not regular expression syntax.[/color]

                    I assume that you want to use the above string as part of the RegExp, so
                    that a matching section can be found in a longer string.

                    S0 = "HELLO[WORLD]" // yours
                    S1 = S0.replace(/([\[\]])/g, "\\$1") // fix-up

                    T0 = "aaaHELLO[WORLD]cccxxxHELLO[WORLD]yyy" // test text

                    RE = new RegExp(S1)
                    T1 = T0.replace(RE, "bbb")

                    RE = new RegExp(S1, "g")
                    T2 = T0.replace(RE, "bbb")

                    A = [T1,,,T2] // results

                    No doubt you will need to fix up any other troublesome characters in S0,
                    by enhancing the line that gives S1.

                    Possibly, one could alternatively fix-up by converting characters to
                    Unicode???


                    *** DO NOT MULTI-POST ***
                    *** READ THE news:C.L.J FAQ ***

                    --
                    © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                    <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                    <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                    <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.

                    Comment

                    • Richard Cornford

                      #11
                      Re: replace string literal

                      Csaba Gabor wrote:
                      <snip>[color=blue]
                      > I tried to modify the String object itself, similarly to the
                      > below (by giving it a self value, to override any original
                      > value), but I didn't get it working (yet?).[/color]
                      <snip>[color=blue]
                      >
                      > function oString(str) {
                      > this.__proto__ = new String(str);
                      > this.toString = function() {return this.__proto__. toString(); };
                      > this.valueOf = function() {return this.__proto__. valueOf(); };
                      > this.selfReplac e = function(needle RegExp, strReplacement) {
                      > this.__proto__ = new String(this.rep lace(needleRegE xp,
                      > strReplacement) ); } }
                      > function changeStr (oStr, newStr) { oStr.selfReplac e(/.*/, newStr); }[/color]
                      <snip>

                      That seems a very extension dependent method of doing what ECMAScript
                      should be able to do by using a String object as the prototype for
                      another object:-

                      function VariableString( st){
                      this.set(st);
                      }
                      VariableString. prototype = new String('');
                      (VariableString .prototype.toSt ring =
                      (VariableString .prototype.valu eOf = function(){
                      return this.value;
                      })
                      );
                      VariableString. prototype.set = function(st){
                      this.value = String(st);
                      this.length = this.value.leng th;
                      };


                      function changeStr(oStr, newStr){
                      oStr.set(oStr.r eplace(/.*/, newStr));
                      }

                      var t = new VariableString( 'yyy')
                      alert(t);
                      changeStr(t, 'xxu xxz');
                      alert(
                      t+' '+
                      '\nindex of u [2] = '+t.indexOf('u' )+
                      '\nlast index of x [5] = '+t.lastIndexOf ('x')+
                      '\nsubstring(4, -1) [xxu ] = "'+t.substring( 4, -1)+'"'+
                      '\ncharAt(2) [u ] = "'+t.charAt(2)+ '"'+
                      '\ncharCodeAt(3 ) [32] = '+t.charCodeAt( 3)+
                      '\nconcat(" ff", 4) [xxu xxz ff4] = '+t.concat(" ff", 4)+
                      '\nmatch("x") [x] = "'+t.match("x") +'"'+
                      '\nsearch("x") [0] = '+t.search("x") +
                      '\nslice(2, 5) [u x] = "'+t.slice( 2, 5)+'"'+
                      '\nsplit("x") [,,u ,,z] = '+t.split("x")+
                      '\ntoUpperCase( ) [XXU XXZ] = "'+t.toUpperCas e()+'"'+
                      '\nlength [7] = '+t.length
                      );

                      - Or using a closure to make the string value of the object private:-

                      function VariableString( st){
                      var value;
                      this.toString = this.valueOf = function(){
                      return value;
                      };
                      this.set = function(st){
                      value = String(st);
                      this.length = value.length;
                      };
                      this.set(st);
                      }
                      VariableString. prototype = new String('');

                      Richard.


                      Comment

                      • gary

                        #12
                        Re: replace string literal


                        Dr John Stockton wrote:[color=blue]
                        > JRS: In article <1149556449.532 678.93950@f6g20 00cwb.googlegro ups.com>,
                        > dated Mon, 5 Jun 2006 18:14:09 remote, seen in
                        > news:comp.lang. javascript, gary <gbrewer@gmail. com> posted :[color=green]
                        > >How would one make the ECMA-262 String.replace method work with a
                        > >string literal?
                        > >
                        > >For example, if my string was "HELLO[WORLD]" how would I make it work
                        > >in this instance.
                        > >
                        > >Please note my square brackets are not regular expression syntax.[/color]
                        >
                        > I assume that you want to use the above string as part of the RegExp, so
                        > that a matching section can be found in a longer string.
                        >
                        > S0 = "HELLO[WORLD]" // yours
                        > S1 = S0.replace(/([\[\]])/g, "\\$1") // fix-up
                        >
                        > T0 = "aaaHELLO[WORLD]cccxxxHELLO[WORLD]yyy" // test text
                        >
                        > RE = new RegExp(S1)
                        > T1 = T0.replace(RE, "bbb")
                        >
                        > RE = new RegExp(S1, "g")
                        > T2 = T0.replace(RE, "bbb")
                        >
                        > A = [T1,,,T2] // results
                        >
                        > No doubt you will need to fix up any other troublesome characters in S0,
                        > by enhancing the line that gives S1.
                        >
                        > Possibly, one could alternatively fix-up by converting characters to
                        > Unicode???
                        >
                        >
                        > *** DO NOT MULTI-POST ***
                        > *** READ THE news:C.L.J FAQ ***
                        >
                        > --
                        > © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                        > <URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
                        > <URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
                        > <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.[/color]


                        Thanks John,

                        Yours seems to be the cloest answer yet.

                        It seems strange I have to handle things like square brackets myself.

                        The same would be the case for all regex special characters, so in
                        reality its not useable to any extent without writing a function which
                        handles everything.

                        Gary

                        Comment

                        • Csaba  Gabor

                          #13
                          Re: replace string literal

                          Richard Cornford wrote:[color=blue]
                          > Csaba Gabor wrote:
                          > <snip>[color=green]
                          > > I tried to modify the String object itself, similarly to the
                          > > below (by giving it a self value, to override any original
                          > > value), but I didn't get it working (yet?).[/color][/color]

                          <example>
                          [color=blue]
                          > That seems a very extension dependent method of doing what ECMAScript
                          > should be able to do by using a String object as the prototype for
                          > another object:-[/color]

                          <example>
                          [color=blue]
                          > - Or using a closure to make the string value of the object private:-[/color]

                          ....

                          Thanks for the nice examples. But is it not possible to modify the
                          String prototype directly? The below code that I tried works in FF,
                          but it fails in IE 6: changeStr works as expected, changing .self on
                          the string object. However, while the revised valueOf and toString
                          methods fire, they do not see (this).self, and I don't see what I'm
                          missing either.

                          Csaba

                          function protoRevamp (obj, strMethod) {
                          var tmpMethod=obj.p rototype[strMethod];
                          obj.prototype[strMethod] = function(oldMet hod) {
                          return function() {
                          if (this.self || this.self=="") return this.self;
                          return oldMethod.apply (this); } } (tmpMethod); }

                          protoRevamp (String, "valueOf");
                          protoRevamp (String, "toString") ;
                          String.prototyp e.selfReplace =
                          function(search RE, strReplacement) {
                          this.self = this.replace(se archRE, strReplacement) ; }

                          function changeStr (oStr, newStr) { oStr.selfReplac e(/.*/, newStr); }

                          var t = new String('yyy');
                          alert ("old t: " + t);
                          changeStr(t, 'xxu xxz');
                          alert(
                          'string [xxu xxz] = "' + t+'"'+
                          '\nself [xxu xxz] = "' + t.self+'"'+
                          '\nlength [7] = '+t.length+
                          '\nindex of u [2] = '+t.indexOf('u' )+
                          '\nlast index of x [5] = '+t.lastIndexOf ('x')+
                          '\nsubstring(4, -1) [xxu ] = "'+t.substring( 4, -1)+'"'+
                          '\ncharAt(2) [u ] = "'+t.charAt(2)+ '"'+
                          '\ncharCodeAt(3 ) [32] = '+t.charCodeAt( 3)+
                          '\nconcat(" ff", 4) [xxu xxz ff4] = '+t.concat(" ff", 4)+
                          '\nmatch("x") [x] = "'+t.match("x") +'"'+
                          '\nsearch("x") [0] = '+t.search("x") +
                          '\nslice(2, 5) [u x] = "'+t.slice( 2, 5)+'"'+
                          '\nsplit("x") [,,u ,,z] = '+t.split("x")+
                          '\ntoUpperCase( ) [XXU XXZ] = "'+t.toUpperCas e()+'"'
                          );

                          Comment

                          • Richard Cornford

                            #14
                            Re: replace string literal

                            Csaba Gabor wrote:[color=blue]
                            > Richard Cornford wrote:[/color]
                            <snip>[color=blue][color=green]
                            >> That seems a very extension dependent method of doing what
                            >> ECMAScript should be able to do by using a String object as
                            >> the prototype for another object:-[/color]
                            >
                            > <example>[color=green]
                            >> - Or using a closure to make the string value of the object private:-[/color]
                            > ...
                            >
                            > Thanks for the nice examples. But is it not possible to modify the
                            > String prototype directly?[/color]

                            Why? What you are proposing is in no way simpler or more obvious/clear
                            that my suggestions.
                            [color=blue]
                            > The below code that I tried works in FF,
                            > but it fails in IE 6: ...
                            >, and I don't see what I'm missing either.[/color]
                            <snip>

                            An appreciation of simplicity apparently.

                            Richard.

                            Comment

                            • Csaba  Gabor

                              #15
                              Re: replace string literal

                              Richard Cornford wrote:[color=blue]
                              > Csaba Gabor wrote:[color=green]
                              > > Richard Cornford wrote:[/color]
                              > <snip>[color=green][color=darkred]
                              > >> That seems a very extension dependent method of doing what
                              > >> ECMAScript should be able to do by using a String object as
                              > >> the prototype for another object:-[/color]
                              > >
                              > > <example>[color=darkred]
                              > >> - Or using a closure to make the string value of the object private:-[/color]
                              > > ...
                              > >
                              > > Thanks for the nice examples. But is it not possible to modify the
                              > > String prototype directly?[/color]
                              >
                              > Why?[/color]

                              Why do I want to know? To further my understanding. I've done
                              almost nothing with prototypes, and it's evident that I don't have
                              a sufficient grasp of them yet. You'd be one of the first people
                              I'd expect to support furthering such understanding.
                              [color=blue]
                              > What you are proposing is in no way simpler or more obvious/clear
                              > that my suggestions.[/color]

                              Nor did I even imply it.
                              [color=blue][color=green]
                              > > The below code that I tried works in FF,
                              > > but it fails in IE 6: ...
                              > >, and I don't see what I'm missing either.[/color]
                              > <snip>
                              >
                              > An appreciation of simplicity apparently.[/color]

                              No, I have a deep appreciation of simplicity. However,
                              without understanding, appreciation tends to be shallow.
                              So to fully appreciate your solution, it makes sense for
                              me to understand why the approach I mentioned can't
                              work or what it would take to shore it up.

                              Csaba

                              Comment

                              Working...