473,772 Members | 2,244 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

replace string literal

How would one make the ECMA-262 String.replace method work with a
string literal?

For example, if my string was "HELLO[WORLD]" how would I make it work
in this instance.

Please note my square brackets are not regular expression syntax.

Thanks,

Gary

Jun 6 '06
21 3411

"Anthony Jones" <An*@yadayadaya da.com> wrote in message
news:%2******** ********@TK2MSF TNGP05.phx.gbl. ..
Thanks John,
Yours seems to be the cloest answer yet.

It seems strange I have to handle things like square brackets myself.


Why does that seem strange? Is it because your more familiar with VBs
replace function?

The replace method takes a RegExp so characters that have meaning in

RegExp will have to be escaped.
The same would be the case for all regex special characters, so in
reality its not useable to any extent without writing a function which
handles everything.


Add this in the top of your javascript:-

String.prototyp e.replaceText = function(search , replacement)
{
search = search.replace( this.rxSpecial, '\\$1')

var regexp = new RegExp(search, "g")

return this.replace(re gexp, replacement)
}
String.prototyp e.rxSpecial =
/(\(|\)|\\|\^|\$ |\||\?|\:|\[|\]|\.|\{|\}|\+|\* |\=|\!)/g

Now you can use this new method like this:-

"HELLO[WORLD]".replaceTe xt("[WORLD]", " Kosmos")

Anthony.

Another thought I've had is that if you want to preform the same replacement
repeatedly then rather than calling replaceText so this is better:-

String.prototyp e.replaceText = function(search , replacement)
{
return this.replace(th is.getRegExpFor Text(search), replacement)
}
String.prototyp e.getRegExpForT ext = function(search )
{
search = search.replace( this.rxSpecial, '\\$1')
return new RegExp(search, "g")
}
String.prototyp e.rxSpecial =
/(\(|\)|\\|\^|\$ |\||\?|\:|\[|\]|\.|\{|\}|\+|\* |\=|\!)/g
Rather then calling replaceText in a loop call getRegExpForTex t before the
loop, keep the returned RegExp object in a variable and use it with the
native replace function in the loop.


Jun 8 '06 #21
Csaba Gabor wrote:
Richard Cornford wrote:
Csaba Gabor wrote:
<snip>
I tried to modify the String object itself, similarly to the
below (by giving it a self value, to override any original
value), but I didn't get it working (yet?).


<example>
That seems a very extension dependent method of doing what ECMAScript
should be able to do by using a String object as the prototype for
another object:-


<example>
- Or using a closure to make the string value of the object private:-

...
Thanks for the nice examples. But is it not possible to modify the
String prototype directly? The below code that I tried works in FF,
but it fails in IE 6: changeStr works as expected, changing .self on


In the beating a dead horse category, I took another approach. Rather
than trying to modify the String prototype directly (on account of IE
wanting to do a "copy" when it saw the string object), I thought
perhaps I could redefine it. And anyway the structure should be
cleaner. Once again, it works in FF and fails (though not so badly) in
IE.

But the failure in IE is still quite bad. Everything is OK except the
..length property is uniformly 0. That is to say, IE's jscript
steadfastly refuses to let me affix a .length property to the revised
String object. It wants to reflect the underlying prototype's .length,
as far as I can tell.
oldString = String;
String = function(st) { this.set(st); }
String.prototyp e = oldString.proto type;
String.prototyp e.toString = function() { return this.value; }
String.prototyp e.valueOf = function() { return this.value; }
String.prototyp e.set = function(replac ement, searchRE) {
if (arguments.leng th<2) this.value = oldString(repla cement);
else this.value = this.replace(se archRE, replacement); }

function changeStr (oStr, newStr) { oStr.set(newStr , /.*/); }

var u = new String('yyy');
var t = new String(u);
alert ("old t: " + t + "\nlength: " + t.length);
changeStr(t, 'xxu xxz');
alert(
'string [xxu xxz] = "' + t+'"'+
'\nlength [7] = '+t.length+
'\nindex of u [2] = '+t.indexOf('u' )+
'\nlast index of x [5] = '+t.lastIndexOf ('x')+
'\nsubstring(4, -1) [xxu ] = "'+t.substring( 4, -1)+'"'+
'\ncharAt(2) [u] = "'+t.charAt(2)+ '"'+
'\ncharCodeAt(3 ) [32] = '+t.charCodeAt( 3)+
'\nconcat(" ff", 4) [xxu xxz ff4] = '+t.concat(" ff", 4)+
'\nmatch("x") [x] = "'+t.match("x") +'"'+
'\nsearch("x") [0] = '+t.search("x") +
'\nslice(2, 5) [u x] = "'+t.slice( 2, 5)+'"'+
'\nsplit("x") [,,u ,,z] = '+t.split("x")+
'\ntoUpperCase( ) [XXU XXZ] = "'+t.toUpperCas e()+'"'
);
alert ("old u: " + u + "\nlength: " + u.length);

Jun 9 '06 #22

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
4042
by: Brian | last post by:
I want to use regxp to check that a form input contains at least 1 non-space charcter. I'd like to only run this if the browser supports it. For DOM stuff, I'd use if (documentGetElementById) {} Is there an object/feature detection I can use to check for regxp string manipulation support? --
5
2720
by: Michael Hiegemann | last post by:
Hello, I am unaware whether this is the right group to ask. Please point me to another forum if required. I would like to replace a Fortran function by one which is written in C. The function shall provide the same interface for the fortran code calling the library. Fortunately, this works - currently under WinNT - well for all functions which do not return a string, e.g.
5
19127
by: Hilary Cotter | last post by:
I'm trying to replace the characters in a pointer from an url string. Here is my code. // string has embedded '+', this code will not work. VOID PatchQuery(char *szQuery, char **ppszPatchedQuery) { char *p = szQuery; while (*p++)
4
4366
by: jgabbai | last post by:
Hi, What is the best way to white list a set of allowable characters using regex or replace? I understand it is safer to whitelist than to blacklist, but am not sure how to go about it. Many thanks!
2
8375
by: Evan | last post by:
Hey, I posted this yesterday, but no one had any ideas? C'mon now, I know this isn't that hard, i'm just a little new to javascript, and I can't quite figure this out. I searched and searched to try and find the answer to this, but I had no luck anywhere. It's a little different situation than I found anywhere else. I would simply put javascript into the <a> tag, but like I said, It's delivered via PHP, and I don't have access to it. I...
5
2383
by: xla76 | last post by:
Can anyone help me, I'm trying to replace any double quotes in a textbox with a different character. mystring = Replace(TextBox.Text , " , "*") I've tried chr(34) and """"" with no luck. Thanks Pete
1
3408
by: NvrBst | last post by:
I want to use the .replace() method with the regular expression /^ %VAR % =,($|&)/. The following DOESN'T replace the "^default.aspx=,($|&)" regular expression with "": --------------------------------- myStringVar = myStringVar.replace("^" + iName + "=,($|&)", ""); --------------------------------- The following DOES replace it though: --------------------------------- var match = myStringVar.match("^" + iName + "=,($|&)");
25
2301
by: magix | last post by:
Hi, I have char* str1 = "d:\temp\data\test.txt" I want to replace all the "\" to be "\\", so that the string will have "d:\\temp\\data\\test.txt" Can you help ?
3
10050
by: Ned White | last post by:
Hi All, To replace some substrings in a string value, i use Regex.Replace method mulptiple times like; strmemo = "new Data for user; Name:@@Name , Surname:@@Surname, Address:@@Address"; strmemo = Regex.Replace(strmemo,"@@Name", value1.ToString()); strmemo = Regex.Replace(strmemo,"@@Surname", value2.ToString()); strmemo = Regex.Replace(strmemo,"@@Address", value3.ToString());
0
9620
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10038
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9912
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8934
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6715
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.