?
Solved

global replace with a variable

Posted on 2005-05-13
2
Medium Priority
?
787 Views
Last Modified: 2007-12-19
truncFilename = filename.substr(0,filename.lastIndexOf("."))
alert(urlPathToXdl.replace(/truncFilename/g,escape(truncFilename)))

the above replace does not work because "truncFilename" is a variable and not a string literal. if I change to:

alert(urlPathToXdl.replace(truncFilename,escape(truncFilename)))

...then the replace works but not globally (only replaces 1st instance).

How do I correctly specify the global replace?
0
Comment
Question by:SweatCoder
2 Comments
 
LVL 36

Accepted Solution

by:
Zyloch earned 1200 total points
ID: 14000461
Hi SweatCoder,

You can either use eval() function, something like:

eval("alert(urlPathToXdl.replace(/"+truncFilename+"/g,escape(truncFilename)));");

The better way would be something like:

var re = new RegExp(truncFilename,"g");
alert(urlPathToXdl.replace(re,escape(truncFilename)));

Regards,
Zyloch
0
 
LVL 32

Assisted Solution

by:Batalf
Batalf earned 800 total points
ID: 14000472
You can use the RegExp object.

example:

truncFilename = filename.substr(0,filename.lastIndexOf("."))
var pattern = new RegExp(truncFilename,"g");
alert(urlPathToXdl.replace(pattern,escape(truncFilename)))

other examples here:

http://www.regular-expressions.info/javascriptexample.html
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question