Str Replace

Discussion in 'Javascript' started by Michael, Feb 16, 2006.

  1. Michael

    Michael Guest

    In PHP there is a function called str_replace
    (http://php.net/str_replace). Basically you can freed in two strings
    and a "subject" string. Then it goes through the subject string
    searching for occurences of the "search" string and replaces them with
    the "replace" string. Is there something simular in JavaScript, or can
    someone give me a solution. I am an experienced PHP user and XHTML
    writer, and I have learnt Javascript to a reasonable level so you don't
    need to explain it too simply but simple enough for a programmer to
    understand.

    Many Thanks,
    Michael Mulqueen.
    Michael, Feb 16, 2006
    #1
    1. Advertising

  2. Michael

    Jambalaya Guest

    Michael wrote:
    > In PHP there is a function called str_replace
    > (http://php.net/str_replace). Basically you can freed in two strings
    > and a "subject" string. Then it goes through the subject string
    > searching for occurences of the "search" string and replaces them with
    > the "replace" string. Is there something simular in JavaScript, or can
    > someone give me a solution. I am an experienced PHP user and XHTML
    > writer, and I have learnt Javascript to a reasonable level so you don't
    > need to explain it too simply but simple enough for a programmer to
    > understand.


    Try the "replace" method of the String[1] object.

    [1]<url:http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Global_Objects:String>
    Jambalaya, Feb 16, 2006
    #2
    1. Advertising

  3. Michael

    VK Guest

    Michael wrote:
    > In PHP there is a function called str_replace
    > (http://php.net/str_replace). Basically you can freed in two strings
    > and a "subject" string. Then it goes through the subject string
    > searching for occurences of the "search" string and replaces them with
    > the "replace" string. Is there something simular in JavaScript, or can
    > someone give me a solution. I am an experienced PHP user and XHTML
    > writer, and I have learnt Javascript to a reasonable level so you don't
    > need to explain it too simply but simple enough for a programmer to
    > understand.


    There is not exact equivalent of srt_replace in JavaScript, but one can
    make an exact equivalent of it using RegExp tools if it's needed.

    If you just need a quick'n'durty solution then:
    ....
    var s1 = "abababababababab";
    var s2 = s1.replace(/a/g,'c');
    alert(s2); // cbcbcb...
    ....

    So: subject.replace(/searchString/g, "replaceString");

    /searchString/g is a regular expression with /g flag to replace all
    occurences, not just the first one.
    VK, Feb 16, 2006
    #3
  4. Michael

    Michael Guest

    Thankyou, that was great advice, but it is so dirty that I have to go
    and wash my hands now :(. Anyway that helps but I also wondered, say if
    I launched a pop up window of blah.html, from the pop up window how
    could I edit a textarea in the main document with this?
    Michael, Feb 16, 2006
    #4
  5. Michael

    VK Guest

    Michael wrote:
    > I launched a pop up window of blah.html, from the pop up window how
    > could I edit a textarea in the main document with this?


    var subject = self.opener.document.forms['Name'].elements['Name'].value;
    VK, Feb 16, 2006
    #5
  6. Michael wrote:

    > Thankyou, that was great advice,


    No, it was not at all.

    > but it is so dirty that I have to go and wash my
    > hands now :(.


    IBTD. Depending on what type the first argument of
    String.prototype.replace() is, it is equivalent to
    PHP's str_replace() or ereg_replace() (and even
    preg_replace(), for the most part). You do not have
    to use Regular Expression( literal)s as VK did. The
    syntax is a bit different though, for PHP is not truly
    an object-oriented or object-based language (there is
    no top-level object, for example). ECMAScript
    implementations are, so strings are also objects.

    <?php
    $s = "foobarbaz";
    $s = str_replace('bar', '', $s);
    ?>

    and

    var s = 'foobarbaz';
    s = s.replace('bar', '');

    are equivalent, where in ECMAScript implementations it
    can even be shorter:

    var s = 'foobarbaz'.replace('bar', '');


    PointedEars
    Thomas 'PointedEars' Lahn, Feb 17, 2006
    #6
  7. Michael wrote:

    > Thankyou, that was great advice,


    No, it was not at all.

    > but it is so dirty that I have to go and wash my
    > hands now :(.


    IBTD. Depending on what type the first argument of
    String.prototype.replace() is, it is equivalent to
    PHP's str_replace() or ereg_replace() (and even
    preg_replace(), for the most part). You do not have
    to use Regular Expression( literal)s as VK did. The
    syntax is a bit different though, for PHP is not truly
    an object-oriented or object-based language (there is
    no top-level object, for example). ECMAScript
    implementations are, so strings are also objects.

    <?php
    $s = 'foobarbaz';
    $s = str_replace('bar', '', $s);
    ?>

    and

    var s = 'foobarbaz';
    s = s.replace('bar', '');

    are equivalent, where in ECMAScript implementations it
    can even be shorter:

    var s = 'foobarbaz'.replace('bar', '');


    PointedEars
    Thomas 'PointedEars' Lahn, Feb 17, 2006
    #7
  8. Michael

    Jambalaya Guest

    VK wrote:
    > Michael wrote:
    > > In PHP there is a function called str_replace
    > > (http://php.net/str_replace). Basically you can freed in two strings
    > > and a "subject" string. Then it goes through the subject string
    > > searching for occurences of the "search" string and replaces them with
    > > the "replace" string. Is there something simular in JavaScript

    [snip]
    > There is not exact equivalent of srt_replace in JavaScript, but one can
    > make an exact equivalent of it using RegExp tools if it's needed.

    [snip]

    Here is a javascript version of PHP's str_replace. It uses the Array's
    "map" and "forEach" methods so those will need to be added to the
    prototype if necessary. Also, since Javascript passes numeric variables
    by value instead of by reference the fourth argument is a callback
    function that returns the replacement count.

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>Javascript str_replace</title>
    <script type="text/javascript">

    function str_replace(search, replace, subject, countfn){
    var replacement, temparr, rplcount=0;
    var searchIsArray = (typeof search == 'object' &&
    search.constructor == Array);
    var replaceIsArray = (typeof replace == 'object' &&
    replace.constructor == Array);
    var subjectIsArray = (typeof subject == 'object' &&
    subject.constructor == Array);

    if (!searchIsArray) search = [search];
    if (!subjectIsArray) subject = [subject];

    var rval = subject.map(
    function(sub){
    search.forEach(
    function(el, i){
    if (replaceIsArray){
    replacement = (i>replace.length-1)?'':replace;
    }else{
    replacement = replace;
    }
    temparr = sub.split(el);
    rplcount += temparr.length - 1;
    sub = temparr.join(replacement);
    }
    );
    return sub;
    }
    );
    if (countfn && typeof countfn == 'function') countfn(rplcount);
    return subjectIsArray?rval:rval[0];
    }


    function init(){
    var cnt=0, str='abc';

    function cfn(x){cnt+=x}

    alert(str_replace('b','x',str,cfn));
    alert(str_replace(['a','c'],'x',str,cfn));
    alert(str_replace(['a','b','c'],['x','y','z'],str,cfn));
    alert('There were ' + cnt + ' replacements made.');
    }
    window.onload = init;
    </script>
    </head>
    <body>
    View the source for the code.
    </body>
    </html>
    Jambalaya, Feb 18, 2006
    #8
  9. Thomas 'PointedEars' Lahn wrote:
    <snip>
    > .... , for PHP is not truly
    > an object-oriented or object-based language
    > (there is no top-level object, for example).
    > ECMAScript implementations are, so strings are
    > also objects.


    Disregarding any (OT) consideration of whether PHP may be
    object-oriented or object-based or not, strings in javascript are
    primitive values by specification. They may be (indeed almost certainly
    are) implemented as objects in some internal sense but they are not
    objects in the sense that ECMA 262 talks of objects.

    <snip>
    > var s = 'foobarbaz';


    At this point the value of - s - is a string primitive (- typeof s -
    returns "string" rather than "object" (as it would with (new
    String('foobarBaz') ) - s instanceof String - is false, and - 'toString'
    in s - will throw an exception).

    > s = s.replace('bar', '');


    It is possible to treat a non-null and non-undefined primitive value as
    objects (use it as the MemberExpression to the left of the dot or
    opening square bracket in a property accessor) because the property
    accessor algorithm implies type-conversion to object. ECMA 262, 3rd ed.
    Section 11.2.1; where step 5 calls the internal - ToObject - function
    with the primitive value as its argument, and string primitives are
    converted to String objects (boolean values to Boolean objects and
    numeric values to Number objects) for the resolution of the property
    accessor. So:-

    s = s.replace('bar', '');

    - is implicitly identical to:-

    s = (new String(s)).replace('bar', '');

    - whenever the value of s is a string primitive.

    > are equivalent, where in ECMAScript implementations it
    > can even be shorter:
    >
    > var s = 'foobarbaz'.replace('bar', '');


    Which is itself implicitly the equivalent of:-

    var s = (new String('foobarbaz')).replace('bar', '');

    However, extermination has shown that this implicit type-conversion is
    so common that implementations optimise the process so much that making
    it explicit is often less efficient than leaving it implicit (at least
    for the case where the implicit type-conversion only happens once, as
    above). This fact supports the notion that the string primitive in
    javascript is indeed internally an object in whatever language is
    implementing the javascript interpreter.

    Richard.
    Richard Cornford, Feb 18, 2006
    #9
  10. Richard Cornford wrote:

    > Thomas 'PointedEars' Lahn wrote:
    >> .... , for PHP is not truly
    >> an object-oriented or object-based language
    >> (there is no top-level object, for example).
    >> ECMAScript implementations are, so strings are
    >> also objects.

    >
    > Disregarding any (OT) consideration of whether PHP may be
    > object-oriented or object-based or not, strings in javascript
    > are primitive values by specification.


    Note the "also"?

    > They may be (indeed almost certainly are) implemented as objects in some
    > internal sense but they are not objects in the sense that ECMA 262 talks
    > of objects.


    The mention of "String objects" in the specification is enough justification
    for me for calling strings objects, depending on the context the "string"
    term is used in.

    > [Explanations] This fact supports the notion that the string primitive
    > in javascript is indeed internally an object in whatever language is
    > implementing the javascript interpreter.


    I knew that already, but full ACK from me nevertheless.


    PointedEars
    Thomas 'PointedEars' Lahn, Feb 18, 2006
    #10
  11. Michael

    VK Guest

    Thomas 'PointedEars' Lahn wrote:
    > Richard Cornford wrote:
    >
    > > Thomas 'PointedEars' Lahn wrote:
    > >> .... , for PHP is not truly
    > >> an object-oriented or object-based language
    > >> (there is no top-level object, for example).
    > >> ECMAScript implementations are, so strings are
    > >> also objects.

    > >
    > > Disregarding any (OT) consideration of whether PHP may be
    > > object-oriented or object-based or not, strings in javascript
    > > are primitive values by specification.

    >
    > Note the "also"?
    >
    > > They may be (indeed almost certainly are) implemented as objects in some
    > > internal sense but they are not objects in the sense that ECMA 262 talks
    > > of objects.

    >
    > The mention of "String objects" in the specification is enough justification
    > for me for calling strings objects, depending on the context the "string"
    > term is used in.
    >
    > > [Explanations] This fact supports the notion that the string primitive
    > > in javascript is indeed internally an object in whatever language is
    > > implementing the javascript interpreter.

    >
    > I knew that already, but full ACK from me nevertheless.



    If you want to say something, say it as obscure as possible to make
    sure that anyone will get lost :-D

    replace() method of String takes two arguments: searchSequence and
    replaceSequence.

    If searchSequence is String than *the first occurence* of this string
    will be replaced by replaceSequence.

    If searchSequence is RegExp then the matches to this RegExp will be
    replaced by replaceSequence. All matches or only the first match is
    determined by the RegExp flags (/g - global, /m - multiline)

    In the OP's case we have to use RegExp and not a string because we need
    to replace *all* occurences, not just the first one.

    P.S. And you don't need to quote half of Books of ECMA to explain this
    as you may notice :)
    VK, Feb 19, 2006
    #11
  12. VK wrote:

    > In the OP's case we have to use RegExp and not a string because we need
    > to replace *all* occurences, not just the first one.


    True.

    ,-<URL:http://php.net/str_replace>
    |
    | str_replace -- Replace all occurrences of the search string with the
    | replacement string


    PointedEars
    Thomas 'PointedEars' Lahn, Feb 19, 2006
    #12
  13. VK wrote:
    <snip>
    > If you want to say something, say it as obscure as possible
    > to make sure that anyone will get lost :-D


    Given that examples of 'explanations' posted by you include:-

    | <script type="text/javascript">
    | void function dummy(args) {
    | alert('Booh!');
    | }
    |
    | window.onload = dummy;
    |
    | ...
    |
    | Function dummy is being parsed and allocated on script load,
    | but void operator prevents the script context to get a reference
    | on the allocated memory heap. So it becomes garbage collector
    | ready right away.

    - you probably should not be trying to give advice to anyone on any
    subject, but particularly clarity of explanation. Clarity is no
    substitute for verisimilitude.

    > replace() method of String takes two arguments: searchSequence
    > and replaceSequence.
    >
    > If searchSequence is String than *the first occurence* of this
    > string will be replaced by replaceSequence.
    >
    > If searchSequence is RegExp then the matches to this RegExp
    > will be replaced by replaceSequence. All matches or only the
    > first match is determined by the RegExp flags (/g - global,
    > /m - multiline)
    >
    > In the OP's case we have to use RegExp and not a string
    > because we need to replace *all* occurences, not just the
    > first one.
    >
    > P.S. And you don't need to quote half of Books of ECMA to
    > explain this as you may notice :)


    On the other hand, if you had looked up the - replace - method of String
    objects in the specification you probably would not have omitted two
    very significant aspects of its behaviour that render the above,
    simplistic, explanation dangerously incomplete.

    You have once again made the mistake of thinking that your superficial
    understanding of javascript is complete to the point of being
    definitive, even after you yourself have had to accept that much that
    has come out of your mind on the subject is utterly fictional.

    Richard.
    Richard Cornford, Feb 20, 2006
    #13
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. David
    Replies:
    2
    Views:
    464
    Thomas G. Marshall
    Aug 3, 2003
  2. Trevor

    sizeof(str) or sizeof(str) - 1 ?

    Trevor, Apr 3, 2004, in forum: C Programming
    Replies:
    9
    Views:
    610
    CBFalconer
    Apr 10, 2004
  3. Sullivan WxPyQtKinter

    It is fun.the result of str.lower(str())

    Sullivan WxPyQtKinter, Mar 7, 2006, in forum: Python
    Replies:
    5
    Views:
    323
    Tim Roberts
    Mar 9, 2006
  4. Stefan Ram

    str.equals(null) or str==null ?

    Stefan Ram, Jul 31, 2006, in forum: Java
    Replies:
    21
    Views:
    14,637
    Oliver Wong
    Aug 3, 2006
  5. maestro
    Replies:
    1
    Views:
    291
    Chris
    Aug 11, 2008
Loading...

Share This Page