Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Str Replace

Reply
Thread Tools

Str Replace

 
 
Michael
Guest
Posts: n/a
 
      02-16-2006
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.

 
Reply With Quote
 
 
 
 
Jambalaya
Guest
Posts: n/a
 
      02-16-2006
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>

 
Reply With Quote
 
 
 
 
VK
Guest
Posts: n/a
 
      02-16-2006

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.

 
Reply With Quote
 
Michael
Guest
Posts: n/a
 
      02-16-2006
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?

 
Reply With Quote
 
VK
Guest
Posts: n/a
 
      02-16-2006

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;

 
Reply With Quote
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      02-17-2006
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
 
Reply With Quote
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      02-17-2006
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
 
Reply With Quote
 
Jambalaya
Guest
Posts: n/a
 
      02-18-2006
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>

 
Reply With Quote
 
Richard Cornford
Guest
Posts: n/a
 
      02-18-2006
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.




 
Reply With Quote
 
Thomas 'PointedEars' Lahn
Guest
Posts: n/a
 
      02-18-2006
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
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
if len(str(a)) == len(str(r)) and isMult(a, r): faster if isMult isslow? maestro Python 1 08-11-2008 01:17 PM
str.equals(null) or str==null ? Stefan Ram Java 21 08-03-2006 06:43 PM
It is fun.the result of str.lower(str()) Sullivan WxPyQtKinter Python 5 03-09-2006 08:09 AM
sizeof(str) or sizeof(str) - 1 ? Trevor C Programming 9 04-10-2004 05:07 PM
what's the deference between str=null and str=" " ???????? David Java 2 08-03-2003 04:10 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57