1

I have 2 strings:

"test:header_footer"
"test_3142"

I want to get array:

array = "test:header_footer".split(":") // ['test', 'header_footer']
array2 = "test_3142".split("_") // ['test', '3142']

Can I combine this with a regex expression to get the same result?

function(s) {
 retutn s.split(/:|_/) // return bad value
}

So if string contain ':' - not separate by second '_'

3
  • 4
    Your conditions are not regular, therefore regular expressions are a poor fit. Instead, first determine if a : is present, and then choose the split character accordingly. Commented Nov 13, 2017 at 13:33
  • your first string contains both : and _, how do you decide which one is the delimiter? Commented Nov 13, 2017 at 13:44
  • @YossiVainshtein ":" - has priority Commented Nov 13, 2017 at 13:47

2 Answers 2

1

You could write a one line method to check for : and split based on that condition.

var text = "your:string";
var array = text.split(text.indexOf(":") >= 0 ? ":" : "_"); // ['your', 'string']

var text2 = "your_string";
var array2 = text.split(text.indexOf(":") >= 0 ? ":" : "_"); // ['your', 'string']

var text3 = "your:other_string";
var array3 = text.split(text.indexOf(":") >= 0 ? ":" : "_"); // ['your', 'other_string']

This will check for :, if that is found then split by :, otherwise split by _.

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

Comments

0

You can use the includes method on your String to determine if there's a : present. If there is split the String by the colon, otherwise split the String by the underscore.

split_string = s => s.includes(":") ? s.split(":") : s.split("_");

//test strings
let str = "my:string_demo",
  str2 = "my_string_demo",
  str3 = "myString:demo_thing",
  //string function
  split_string = s => s.includes(":") ? s.split(":") : s.split("_");


console.log(
  str, split_string(str)
);
console.log(
  str2, split_string(str2)
);
console.log(
  str3, split_string(str3)
);

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.