1

I have a string like below

var exampleString = "Name:Sivakumar ; Tadisetti;Country:India"

I want to split above string with semi colon, so want the array like

var result = [ "Name:Sivakumar ; Tadisetti", "Country:India" ]

But as the name contains another semi colon, I am getting array like

var result = [ "Name:Sivakumar ", "Tadisetti", "Country:India" ]

Here Sivakumar ; Tadisetti value of the key Name

I just wrote the code like exampleString.split(';')... other than this not able to get an idea to proceed further to get my desired output. Any suggestions?

Logic to split: I want to split the string as array with key:value pairs

6
  • 1
    What is the logic that defines which ; to split at ? There are 2 semi-colons in your string. Commented Apr 26, 2020 at 18:17
  • @GabrielePetrioli I want to split the string with key:value pairs Commented Apr 26, 2020 at 18:19
  • 1
    @Leonardo No "Sivakumar ; Tadisetti" is a single value Commented Apr 26, 2020 at 18:24
  • @GabrielePetrioli key doesn't contains semicolons, but value may contain more than one semicolon ex: Name:Sivakumar ; Tadisetti, Country:India Commented Apr 26, 2020 at 18:25
  • 1
    Does a value always end with a semicolon? Commented Apr 26, 2020 at 18:32

2 Answers 2

3

Since .split accepts regular expressions as well, you can use a one that matches semicolons that are only followed by alphanumeric characters that end in : (in effect if they are followed by another key)

/;(?=\w+:)/

var exampleString = "Name:Sivakumar ; Tadisetti;Country:India";
var result = exampleString.split(/;(?=\w+:)/);
console.log(result)

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

1 Comment

dude; nice and clean.
1

here is an approach which we first split the input on ; and then concat the element without : with the previous one; since it shouldn't being spited.

let exampleString = "Name:Sivakumar ; Tadisetti;Country:India"
let reverseSplited = exampleString.split(";").reverse();

let prevoiusString;
let regex = /[^:]+:.*/;

let result = reverseSplited.map( str => {
  if(regex.test(str)) {
    if(prevoiusString){
     let returnValue = str + ";" + prevoiusString;
     prevoiusString = null;
     return returnValue
    }
    return str
  }
  prevoiusString = str;
}).filter(e=>e);


console.log(result);

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.