473,386 Members | 1,962 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,386 software developers and data experts.

String replacement problem

I have an associative array of keys and values. I want to search a
string for the existance of keys and replace them with the values in
the array. The problem is that some of the keys resemble regular
expressions but they are not so if I build the regular expression with
a constructor it causes errors saying that the regular expression
syntax is bad. I got around this problem by skipping the regular
expression method and passing in the key directly as the first argument
of replace however this means I lose the ability to pass the /g global
switch to the replace function so it only replaces once.

So my question is: is there a way to incorperate a variable into a
regex without enterpreting the variable as a regex itself or
alternately is there a way to make the replacement global without using
a regular expression?

Jul 23 '05 #1
4 1566
an************@gmail.com wrote:
I have an associative array of keys and values. I want to search a
string for the existance of keys and replace them with the values in
the array. The problem is that some of the keys resemble regular
expressions but they are not so if I build the regular expression with
a constructor it causes errors saying that the regular expression
syntax is bad. I got around this problem by skipping the regular
expression method and passing in the key directly as the first argument
of replace however this means I lose the ability to pass the /g global
switch to the replace function so it only replaces once.

So my question is: is there a way to incorperate a variable into a
regex without enterpreting the variable as a regex itself or
alternately is there a way to make the replacement global without using
a regular expression?


Do you have a small example to illustrate? Special characters within
regular expressions can be quoted to remove their special-ness,
however I'm not sure they are suitable to use as keys for the
elements of an array.
--
Rob
Jul 23 '05 #2
If the string contains something (usually punctuation or control characters)
that has a special meaning when converted to a regular expression, you have
to escape it ('.' becomes('\.') before the string is converted.

This involves looking at each character in each string and testing it
against a list of suspects [\.\+\=\(\)\&\#\^\$\!\?].

Or you can make each string a new RegExp when you populate the array, and
make a
String.prototype.convertToRegExp() method to escape characters based on
their charCode.

It would be a little less elegant and a bit more efficient to use string
methods.

You can fake a global replace replace by running a regular replace through a
"while" loop:

while(str.indexOf('badString')!=-1)str=str.replace('rString','someotherString').

Both methods work, both have pros and cons.


Jul 23 '05 #3
an************@gmail.com writes:
I have an associative array of keys and values. I want to search a
string for the existance of keys and replace them with the values in
the array. The problem is that some of the keys resemble regular
expressions
Ok, so if you want to use regular expressions for the search, the
keys need to be escaped (i.e., characters meaningfull to a regular
expression must be prefixed with a backslash).

Try this:
---
function replace(string, map) {
var i=0;
var keys = [];
for(var key in map) {
keys[i++] = key.replace(/([\\.+*?()[{|^$])/g,"\\$1"); // escape chars
}
var re = new RegExp(keys.join("|"),"g");
return string.replace(re, function(key) { return map[key]; });
}
---
(this uses the RegExp way of handling overlapping matches, i.e., if you
match for /foo|ok/g then "fook" only matches "foo" and not the overlapping
"ok").
So my question is: is there a way to incorperate a variable into a
regex without enterpreting the variable as a regex itself
Yes, escape character meaningfull in a RegExp
or alternately is there a way to make the replacement global without
using a regular expression?


Probably, but not easier in any way.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #4

A string var is a string var, a regexp is a regexp, there's no way to
confuse a regexp from a string even if the content character wise maybe
the same, they're different types, so, it isn't it, as for to using a
variable for a regexp, you use the new RegExp() constructor and escape the
reserved chars if any:

var duck='\\w+(\\bflying\\b)?'; var myregexp=new
RegExp(duck+'BOLOGNE\\s*$','gi');

If the argument is coming from a form input field, those use
text/plain and any reserved chars are escaped by default.

Danny

On Fri, 17 Jun 2005 17:02:24 -0700, <an************@gmail.com> wrote:
I have an associative array of keys and values. I want to search a
string for the existance of keys and replace them with the values in
the array. The problem is that some of the keys resemble regular
expressions but they are not so if I build the regular expression with
a constructor it causes errors saying that the regular expression
syntax is bad. I got around this problem by skipping the regular
expression method and passing in the key directly as the first argument
of replace however this means I lose the ability to pass the /g global
switch to the replace function so it only replaces once.

So my question is: is there a way to incorperate a variable into a
regex without enterpreting the variable as a regex itself or
alternately is there a way to make the replacement global without using
a regular expression?


--
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
Jul 23 '05 #5

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

Similar topics

3
by: Juha Suni | last post by:
Hi! I have managed to live without using too much regular expressions so far, and now that I need one, I need some help too. I have a string containing a (possibly large) block of html. I need...
5
by: Roose | last post by:
How can I do a "".replace operation which tells me if anything was actually replaced? Right now I am doing something like: if searchTerm in text: text = text.replace( searchTerm, 'other' ) ...
7
by: VMI | last post by:
If I have the string "Héllo", how can I replace char (é) with an 'e'? I cannot use the String.Replace() fuction. It has to be by replacing one char with another. Thanks.
32
by: tshad | last post by:
Can you do a search for more that one string in another string? Something like: someString.IndexOf("something1","something2","something3",0) or would you have to do something like: if...
35
by: jacob navia | last post by:
Hi guys! I like C because is fun. So, I wrote this function for the lcc-win32 standard library: strrepl. I thought that with so many "C heads" around, maybe we could improve it in a...
29
by: zoltan | last post by:
Hi, The scenario is like this : struct ns_rr { const u_char* rdata; }; The rdata field contains some fields such as :
21
by: gary | last post by:
How would one make the ECMA-262 String.replace method work with a string literal? For example, if my string was "HELLO" how would I make it work in this instance. Please note my square...
5
by: ThatVBGuy | last post by:
Hello All, I could really use some help with this problem its driving me nuts. I have a small vb app, the goal of the app is to read an html doc into a variable then go through that variable and...
5
by: int main(void) | last post by:
Hi all, Following is my attempt to write a string search and replace function. #include <stdio.h> #include <stdlib.h> #include <string.h>...
2
Samishii23
by: Samishii23 | last post by:
I know this is simple. Have a small to large string. Replace a 'Key' within that string with what I want replaced... Heres a small example, then the issue I'm having in my head... /* One...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...

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.