By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,458 Members | 1,215 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,458 IT Pros & Developers. It's quick & easy.

Str Replace

P: n/a
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.

Feb 16 '06 #1
Share this Question
Share on Google+
12 Replies


P: n/a
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:Strin g>

Feb 16 '06 #2

P: n/a
VK

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.

Feb 16 '06 #3

P: n/a
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?

Feb 16 '06 #4

P: n/a
VK

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;

Feb 16 '06 #5

P: n/a
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
Feb 17 '06 #6

P: n/a
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
Feb 17 '06 #7

P: n/a
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[i];
}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>

Feb 18 '06 #8

P: n/a
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.


Feb 18 '06 #9

P: n/a
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
Feb 18 '06 #10

P: n/a
VK

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 :-)

Feb 19 '06 #11

P: n/a
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
Feb 19 '06 #12

P: n/a
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.
Feb 20 '06 #13

This discussion thread is closed

Replies have been disabled for this discussion.