473,395 Members | 1,437 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Str Replace

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
12 7276
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
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
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
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
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
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Craig Keightley | last post by:
Can these lines of sql statements be consolidated into one sql statement (possibly using reg exps??) BEGIN CODE ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Update...
12
by: Barnes | last post by:
Does anyone know of a good way to use the JavaScript string.replace() method in an ASP form? Here is the scenario: I have a form that cannot accept apostrophes. I want to use the replace() so...
6
by: Danny | last post by:
I need an asp command to strip out from a string all extra punctuation such as apostrophe, comma, period, spaces dashes, etc etc and just leave the letters. Can anybody give me some ideas? ...
9
by: Peter Row | last post by:
Hi, I know this has been asked before, but reading the threads it is still not entirely clear. Deciding which .Replace( ) to use when. Typically if I create a string in a loop I always use a...
4
by: Cor | last post by:
Hi Newsgroup, I have given an answer in this newsgroup about a "Replace". There came an answer on that I did not understand, so I have done some tests. I got the idea that someone said,...
3
by: Goran Djuranovic | last post by:
Hi all, I ran into a problem where my XMLTextReader fails on .Read() when I have "<" character in one of the attribute's values. What I am trying to do is replace illegal characters ("<", "&" ,...
3
by: TOXiC | last post by:
Hi everyone, First I say that I serched and tryed everything but I cannot figure out how I can do it. I want to open a a file (not necessary a txt) and find and replace a string. I can do it...
6
by: JackpipE | last post by:
Here is my replace query and I need to run this on every column in my table. Right now I manually enter the column name (_LANGUAGES_SPOKEN) but this is time consuming and would like to automate...
5
by: V S Rawat | last post by:
I was trying to use back-to-back replace functions to convert a url: str1 = str.replace("%2F","/").replace("%3F","?").replace("%3D","=").replace("%2 6","&"); It didn't replace all 4 types of...
15
by: =?Utf-8?B?TWlrZSAiWU9fQkVFIiBC?= | last post by:
I have a text file that contains about 8 to 10 text sequences that I need to replace. I want to search and replace all 8 to 10 text sequence anytime I run this script Here is what I have so...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.