Str Replace

M

Michael

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.
 
J

Jambalaya

Michael said:
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>
 
V

VK

Michael said:
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.
 
M

Michael

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?
 
V

VK

Michael said:
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;
 
T

Thomas 'PointedEars' Lahn

Michael said:
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
 
T

Thomas 'PointedEars' Lahn

Michael said:
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
 
J

Jambalaya

VK said:
Michael said:
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>
 
R

Richard Cornford

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. 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.

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.
 
T

Thomas 'PointedEars' Lahn

Richard said:
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
 
V

VK

Thomas said:
Richard said:
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 :)
 
T

Thomas 'PointedEars' Lahn

VK said:
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
 
R

Richard Cornford

VK wrote:
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.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top