global replace with a variable

Posted on 2005-05-13
Last Modified: 2007-12-19
truncFilename = filename.substr(0,filename.lastIndexOf("."))

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


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

How do I correctly specify the global replace?
Question by:SweatCoder
    LVL 36

    Accepted Solution

    Hi SweatCoder,

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


    The better way would be something like:

    var re = new RegExp(truncFilename,"g");

    LVL 32

    Assisted Solution

    You can use the RegExp object.


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

    other examples here:

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    A common challenge, or question, when working with two calendar dates is: What is the difference between the specified days? As is frequently the case, the answer is: It depends... What kind of difference do you want? Given two date obje…
    This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
    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…

    761 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

    Need Help in Real-Time?

    Connect with top rated Experts

    7 Experts available now in Live!

    Get 1:1 Help Now