#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2017
    Posts
    10
    Rep Power
    0

    JavaScript - Non-RegEx String Replace Function!


    This is a Non-RegEx String Replace Function!

    All RegEx special characters from "Match" and "Replace" parameters are automatically escaped!

    As easy as:

    StringReplace(UserString, "\\", "@", "gi");
    StringReplace(UserString, "/", "@", "gi");
    StringReplace(UserString, ".", "@", "gi");
    StringReplace(UserString, "*", "@", "gi");
    StringReplace(UserString, "A", "@", "gi");
    StringReplace(UserString, "B", "@", "gi");
    StringReplace(UserString, "C", "@", "gi");

    StringReplace(UserString2, ".*+?^${}()|[]\\", "$& $$& $$$&", "gi");
    StringReplace(UserString2, ".*+?^${}()|[]\\", "$1 $$2 $$$3", "gi");

    Straight Tips: JavaScript - Non-RegEx String Replace Function
  2. #2
  3. Impoverished Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,884
    Rep Power
    9646
    ...which works by doing a regex string replace. Twice, even.

    Source code so people can avoid giving traffic to the blog:
    javascript Code:
     
    function StringReplace(String = "", Match = "", Replace = "", Options = "") {   //__________________ StringReplace(Function) v1.0 ___________________
     
    //arguments (parameters) work as local variables inside functions!
     
    //Escape RegEx "Match" variable special characters ($& means the whole matched string)
    //Source: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" target="_blank">https://developer.mozilla.org/en-US/...ar_Expressions</a>
    Match = Match.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
     
    //Escape RegEx "Replace" variable special character ($$ = literal $)
    //Necessary in order to avoid backreferences such as $1, $2, $&, etc
    Replace = Replace.replace(/\$/g, "$$$$")
     
    String = String.replace(RegExp(Match, Options), Replace);
     
    return String;
     
    };
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2017
    Posts
    10
    Rep Power
    0
    Originally Posted by requinix
    ...which works by doing a regex string replace. Twice, even.
    Actually, it uses regex Thrice!

IMN logo majestic logo threadwatch logo seochat tools logo