1

I need to remove a prefix from a string. Given an array of known prefixes, I do not know which prefix will exist in a string. One and only one prefix will exist.

    function CleanupSupportedItems(data) {
        var prefixes = new Array("TrialLeads", "IPG");

        for (var i = 0; i < prefixes.length - 1; i++) {
            var prefix = new RegExp(/prefixes[i]/g);
            //alert(prefix);
            data = data.replace(prefix, "");
            alert(data);
        }
    }

The above code returns undefined on the second iteration.

Given the call

CleanupSupportedItems("TrialLeads11");

I want a return value of "11". How can I do it?

2
  • If the resulting values are going to be numbers it would be easier to filter that out.... Commented Aug 23, 2011 at 21:28
  • @sg3s - Yes return values will always be numeric. So whatever suggestions you have for this type of improvement are welcome. Commented Aug 23, 2011 at 21:28

6 Answers 6

4

You can do without the loop:

function CleanupSupportedItems(data) {
    var prefixes = new Array("TrialLeads", "IPG");

    var prefix = new RegExp('^(' + prefixes.join('|') + ')', "g");
    data = data.replace(prefix, "");
    alert(data);
}

CleanupSupportedItems("TrialLeads11");  // alerts 11
CleanupSupportedItems("IPG12");   // alerts 12

Here's demo: http://jsfiddle.net/mrchief/KkRFp/

Updated to make sure it replaced only prefixes and not in between body. Thanks to minitech for pointing it out.

As a suggested improvement, if the input prefixes are expected to have Regex Special characters, they would need to be escaped.

Sign up to request clarification or add additional context in comments.

12 Comments

Ooh, I like your use of join to solve the problem I mentioned in my answer :) +1. You should return data; too I think.
@PaulPRO: I just modified the OP's code. He can do whatever since his original issue is fixed now. :)
-1 Doesn't work for everything - what if someone wanted to remove a prefix ? or ^ or $ or ` or .` or ( or [ or {... (you get the idea). jsfiddle.net/minitech/KkRFp/1
@minitech: That wasn't in the scope of OP's post. You can obviously expand upon this code.
@minitech Agree with MrChief here, the OP would have mentioned if his prefix could contain special regex characters.
|
2

You're not creating your RegExp object correctly, do this instead:

var prefix = new RegExp('^'+prefixes[i], 'g');

After the loop you should also return data;

Note that if you ever have a string like 'TrailheadsIPG11', the result will be '11', since you don't exit the loop when a replace is successful, and if your prefixes array contains any of the characters ()[]{}.*+? or sequences with special meanings in a regex like \d \w \s etc. They will be treated as regex, not as characters. If you want to preserver that functionality you can just escape your characters like \. instead of ..

4 Comments

Also replaces all instances, not just a single one, regardless of position in string, and fails to escape special characters, or even basic punctuation.
@minitech That is what it is meant to do :)
@minitech oh nevermind, I get it now. I added the ^ to make it only match at the start of the string. I don't think punctuation needs to be escaped because the OP's prefixes array doesn't contain any. He would have likely mentioned if the prefixes array could contain any special regex characters
Okay, -1 removed, but you should still escape the data or at least mention a possible problem. We don't know much about the actual application.
1

If the value is always numeric and at the end of the string:

var int = string.match(/[\d]+$/);
if(typeof int != 'undefined')
{
   // There should be a valid (numeric) match in int at this point
}

Should capture all the numbers directly on the end of the string without going into complex loops and ridiculous regexes.

For multiple values ofcourse just loop through them with this inside.

Comments

1
RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};

if(![].map) Array.prototype.map = function(f) { var r = [], i; for(i = 0; i < this.length; i++) r.push(f(this[i])); return r; };

function CleanupSupportedItems(data) {
    var prefixes = ["TrialLeads", "IPG"];

    return data.replace(new RegExp('^(' + prefixes.map(RegExp.escape).join('|') + ')'), ''); // this line changed
}

Should do the job. And it does: http://jsfiddle.net/minitech/XZwLU/ (and http://jsfiddle.net/minitech/XZwLU/1/ for a more complicated example)

EDIT: I just noticed that you said there would only be one prefix, in the question. That's fixed now.

Comments

1

I would build a regex dynamically based on the list of prefixes and replace them with the empty string:

function trimPrefixes(s, ps) {
   return (""+s).replace(new RegExp('^(' + ps.join('|') + ')'), '');
}
// For example...
trimPrefixes("Foo123", ['Foo', 'Bar']); // => "123"
trimPrefixes("Barzip", ['Foo', 'Bar']); // => "zip"
trimPrefixes("I'm ok", ['Foo', 'Bar']); // => "I'm ok"

You could also turn that function into a generator if performance is a concern and you've got varying sets of prefixes that will be used repeatedly.

Comments

-1

You need to be careful when passing variable strings to the regexp object. Try something like this:

function CleanupSupportedItems(data) {
    var prefixes = new Array("TrialLeads", "IPG");

    for (var i = 0; i < prefixes.length - 1; i++) {

        var prefix = new RegExp(prefixes[i], "g");
        //alert(prefix);
        data = data.replace(prefix, "");
    }
              alert(data);
}

CleanupSupportedItems("TrialLeads11");

1 Comment

Again, not escaped, will replace anywhere in the string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.