2

I have String

var t = '@qf$q>@gf';

and array of separators

var s = '@$>';

I would like to have a function which returns:

var a = f(t,s);
// a is array = ["@","qf","$","q",">","@","gf"];

Can you help me ?

2 Answers 2

3

You can use a regular expression:

'@qf$q>@gf'.match(/[@$>]|[^@$>]+/g)

The regular expression /[@$>]|[^@$>]+/g matches all occurrences of either a single separator character ([@$>]) or any sequence of one or more non-separator characters ([^@$>]+).

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

Comments

1

Here is your code:

var t = '@qf$q>@gf';
var s = '@$>';

var finalArray = [];
var tmpString = '';
var found = false;
for (var i=0; i<t.length; i++) {
  for (var j=0; j<s.length; j++) {
    if (t[i] == s[j]) {
      found = true;
      if (tmpString != '') {
        finalArray.push(tmpString);
      }
      finalArray.push(t[i]);
      tmpString = '';
    }
  }
  if (!found) {
    tmpString += t[i];
  }
  found = false;
}
if (tmpString != '') {
  finalArray.push(tmpString);
}

It will output:

["@", "qf", "$", "q", ">", "@", "gf"]

Here is the associated jsFiddle: http://jsfiddle.net/Cf8LA/


Edit: simplified version

var t = '@qf$q>@gf';
var s = '@$>';

var finalArray = [];
var tmpString = '';
for (var i=0; i<t.length; i++) {
  if (s.indexOf(t[i]) >= 0) {
    if (tmpString != '') {
      finalArray.push(tmpString);
    }
    finalArray.push(t[i]);
    tmpString = '';
  } else {
    tmpString += t[i];
  }
}
if (tmpString != '') {
  finalArray.push(tmpString);
}

Updated jsFiddle here: http://jsfiddle.net/Cf8LA/1/

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.