0

I'm trying to generate an array of elements that are either text or an "image block".

var str : String = "";

for (var i : int = 0; i < 100; i++)
{
    str += (Math.random() > .5) ? "<img>amazed</img>" : "<img>happy</img>";
}

var arr : Array = str.split(/(<img>\w+<\/img>)/);

I want the array to have a length of 100 and for each element in the array to reflect either <img>amazed</img> or <img>happy</img>. Instead, the length is 201 and every other element is an empty String.

Is there a simple way to change the regex to avoid doubling the size of the array?

2
  • Why don't you fill the array directly? Why regex? Commented Jul 13, 2018 at 10:58
  • Because the for loop just generates a sample string for testing that'll get input by a user in the future instead of tacked together by a for loop. Edit: Thanks for your answer! Commented Jul 17, 2018 at 9:33

1 Answer 1

2

String.split(...) splits the given string by the provided separator rather then searches for them.

In order to find all matches with RegEx you need to use String.match(...) method:

var S:String = "";

for (var i:int = 0; i < 100; i++)
{
    S += (Math.random > .5)? "<img>amazed</img>": "<img>happy</img>";
}

// Pay attention to the greedy 'g' flag, if you don't set it,
// you will get the first match only as the result.
var R:RegExp = /<img>\w+<\/img>/g;
var A:Array = S.match(R);
Sign up to request clarification or add additional context in comments.

Comments

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.