0

How to skip double ; and omit last ; from string;

function myFunction() {
  var str = "how;are;you;;doing;";
  var res = str.split(";");

  console.log(res[3]);
  console.log(res);
}

myFunction();

it should return how,are,you,doing

should be like console.log(res[3]) = it should says doing not blank

1

5 Answers 5

5

Try this:-

var str = "how;are;you;;doing;";

var filtered = str.split(";").filter(function(el) {
  return el != "";
});

console.log(filtered);

Output:

[ "how", "are", "you", "doing" ]
Sign up to request clarification or add additional context in comments.

Comments

2

You can filter empty strings after splitting:

var str = "how;are;you;;doing;";

console.log(str.split(';').filter(Boolean));

Comments

1

You could do this

var a = "how;are;you;;doing;";
a = a.split(';').filter(element => element.length);

console.log(a);

Comments

0

The below function definition is in ES6:

let myFunction = () => {
  let str = "how;are;you;;doing;";
  return str.split(';').filter((el) => {
    return el != "";
  });
}

Now you can simply log the output of the function call.

console.log(myFunction());

Comments

0

Use split for converting in an array, remove blank space and then join an array using sep",".

function myFunction(str) {
  var res = str.split(";");
  res = res.filter((i) => i !== "");
  console.log(res.join(","));
}

var str = "how;are;you;;doing;";
myFunction(str);

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.