0

I'm a Javascript noob using regex in javascript to globally replace text on web page. Easy enough.

v = v.replace(/\Simon\b/g, "JS Noob");

I know I can replace with functions, but I can't get this to work:

v = v.replace(/\bSimon\b/g, function(replaceLoop) {
    var myStringArray = ["herp","derp","clueless","hurrrrr"];
    var arrayLength = myStringArray.length;
    for (var i = 0; i < arrayLength; i++){
        replaceLoop = myStringArray;
        return replaceLoop;
    } 
}

I have a feeling I'm thinking about this all wrong.

3
  • and the question is.....? Commented Jun 4, 2014 at 15:28
  • What exactly are you trying to do? Also provide your input and expected output? Commented Jun 4, 2014 at 15:28
  • What does replaceLoop return exactly? Commented Jun 4, 2014 at 15:29

2 Answers 2

2

Step 1, make a function which returns the next item from an Array each time

function iterGen(arr, i) {
    i || (i = 0);
    return function () {
        i %= arr.length;
        return arr[i++];
    };
}

Step 2, pass this into your replace

v = v.replace(/\bSimon\b/g, iterGen(["herp","derp","clueless","hurrrrr"]));
Sign up to request clarification or add additional context in comments.

4 Comments

Interesting, I took it as OP wanting a random index instead of iterating through with each replacement.
Starting form JS 1.7 you can simply do var arr = [1, 2, 3], it = arr.iterator(), next = it.next.bind(it);
@plalx I really like some things in 1.7, and many are re-designed and included in ES 6, but you can't rely on browser support for 1.7 - it's basically gecko only
I was unclear in my question... I was actually looking for a random index that, not really stepping through, since that would reach the end of the array. However, this is helpful and answers another question that I know I'll run into. Thank you.
0

A quick syntax error is causing issues, you are missing the closing ); to .replace(). Also, you are setting replaceLoop = myStringArray instead of a specific string. Assuming you want a random index, you'll need Math.random().

v = v.replace(/\bSimon\b/g, function(replaceLoop) {
    var myStringArray = ["herp","derp","clueless","hurrrrr"];
    var arrayLength = myStringArray.length;
    var index = Math.floor(Math.random() * arrayLength);

    return myStringArray[index];
});

1 Comment

That's exactly it! I had a syntax error AND a conceptual mistake. Your answer solves both... thank you!

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.