1

I have a string in which every value is between [] and it has a . at the end. How can I separate all values from the string?

This is the example string:

[value01][value02 ][value03 ]. [value04 ]

//want something like this 
v1 = value01;
v2 = value02;
v3 = value03;
v4 = value04  

The number of values is not constant. How can I get all values separately from this string?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
user3713959
  • 101
  • 1
  • 13

3 Answers3

2

Use regular expressions to specify multiple separators. Please check the following posts:

How do I split a string with multiple separators in javascript?

Split a string based on multiple delimiters

var str = "[value01][value02 ][value03 ]. [value04 ]"
var arr = str.split(/[\[\]\.\s]+/);
arr.shift(); arr.pop(); //discard the first and last "" elements
console.log( arr ); //output: ["value01", "value02", "value03", "value04"]

JS FIDDLE DEMO

How This Works

.split(/[\[\]\.\s]+/) splits the string at points where it finds one or more of the following characters: [] .. Now, since these characters are also found at the beginning and end of the string, .shift() discards the first element, and .pop() discards the last element, both of which are empty strings. However, your may want to use .filter() and your can replace lines 2 and 3 with:

var arr = str.split(/[\[\]\.\s]+/).filter(function(elem) { return elem.length > 0; });

Now you can use jQuery/JS to iterate through the values:

$.each( arr, function(i,v) {
    console.log( v ); // outputs the i'th value;
});

And arr.length will give you the number of elements you have.

Community
  • 1
  • 1
PeterKA
  • 24,158
  • 5
  • 26
  • 48
0

If you want to get the characters between "[" and "]" and the data is regular and always has the pattern:

'[chars][chars]...[chars]'

then you can get the chars using match to get sequences of characters that aren't "[" or "]":

var values = '[value01][value02 ][value03 ][value04 ]'.match(/[^\[\]]+/g) 

which returns an array, so values is:

["value01", "value02 ", "value03 ", "value04 "]

Match is very widely supported, so no cross browser issues.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

Here's a fiddle: http://jsfiddle.net/5xVLQ/

Regex patern: /(\w)+/ig
Matches all words using \w (alphanumeric combos). Whitespace, brackets, dots, square brackets are all non-matching, so they don't get returned.

What I do is create a object to hold results in key/value pairs such as v1:'value01'. You can iterate through this object, or you can access the values directly using objRes.v1

var str = '[value01][value02 ][value03 ]. [value04 ]';
var myRe = /(\w)+/ig;
var res;
var objRes = {};
var i=1;
while ( ( res = myRe.exec(str) ) != null )
{
    objRes['v'+i] = res[0];
    i++;    
}
console.log(objRes);
Dave Briand
  • 1,684
  • 1
  • 16
  • 16