0

I have a string like this, Fy 2002.car.state.

I need to split this based on value, if the value is 0 I need split like "Fy 2002","car","state" separately.If the value is 1, I need split like this "Fy 2002.car","state".

How do I achieve this without using for loop? Thanks.

5
  • 1
    is it possible that index = 2? and if so, what should be the result look like? Commented Aug 27, 2015 at 11:02
  • 1
    Its really hard to understand what your expecting since there is no progressive flow in your requirement Commented Aug 27, 2015 at 11:07
  • 1
    Do you have only spaces and dots to seperate? Commented Aug 27, 2015 at 11:21
  • 1
    What “index”? What is the data structure here? Commented Aug 27, 2015 at 11:42
  • I have a string "Fy 2002.car.state", if i split this by '.' it will be splitted like ["Fy 2002","car","state"]. If i have array index as 0 means it shows "Fy 2002", if 1 means, i need string "Fy 2002.car", for 2 will be like "Fy 2002.car.state" this and so on.... Commented Aug 27, 2015 at 13:22

3 Answers 3

1

First create the array using split.
Then cut off the array using splice.
Finally join the cut items using join and put it into array.

function mysplit(str, index){
  var a = str.split('.')
  if(index){
    a[0] += '.' + a.splice(1, index).join('.')
  }
  return a
}

Other possibility is to use a reduce function.

function mysplit2(str, index){
  var a = str.split('.')
  if(index){
    a = a.reduce(function(p, c, i) {
      p.push(c)
      return (i <= index ? [p.join('.')] : p)
    },[])
  }
  return a
}
Sign up to request clarification or add additional context in comments.

Comments

1

My interpretation of the question

  • split the string
  • join the first nth elements with .

var str = "Fy 2002.car.state",
    a = str.split('.');

function split(a, index) {
    if (index) {
        a[0] +=  '.' + a.splice(1, index).join('.');
    }			
    document.write('<pre>' + index + ' ' + JSON.stringify(a, 0, 4) + '</pre>');
}

split(a.slice(0), 0);
split(a.slice(0), 1);
split(a.slice(0), 2);

1 Comment

yes. What i am exactly expecting. logic works for me.
0

You can do it with split

var str="Fy 2002.car.state";
var result= str.split('.');

Fiddle Here

2 Comments

@ozil Let OP decide don't you think?
I think giving complete answer is more appropriate

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.