Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to split a string dynamically that may have different format(a:b,a.b,a/b) to an array of two elements.For example :

string :- abs:sba;//array[0]='abs';array[1]='sba';
string :- abs.sba;//array[0]='abs';array[1]='sba';
string :- abs/sba;//array[0]='abs';array[1]='sba';

I have tried with string.split(':'); method,but it will not be applicable for the next two cases.I need a solution which split the string dynamically.

share|improve this question
use the delimiter ":" – AnaMaria 11 hours ago
6  
You forgot the second paragraph: "This is what I tried but it didn't work: code" – elclanrs 11 hours ago
is it always split by the middle? – koala_dev 11 hours ago
Do you have a list of valid delimiters? – Alxandr 10 hours ago
You should have a list of delimiters – MrROY 10 hours ago

3 Answers

up vote 3 down vote accepted

You can use regex to specify multiple delimiters in a character class:

yourString.split(/[:;,\/]/);

Specify all possible delimiters inside [] in the regex.

share|improve this answer

Lets say your string is a variable 'a'

var a = "What,have/you-tried".split(",/-") // Delimiter is a string
for (var i = 0; i < a.length; i++)
{
    alert(a[i])
}

This will give us an array of the words you want eliminating the characters you use in the split function which in this case is ,/-

share|improve this answer

You can use split function:

var arr = str.split(/[:.\/]/);

OR if you want to split the string using any non-word character then use:

var arr = str.split(/\W/);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.