Reputation: 1816
I have this string: 'foo = bar; this = is; not = necessary'
I would like to get this result: {"name" : "foo", "value" : "bar"}
It is not necessary, what is after the ;
I know, I should use some regexp, but I don't really understand how regexp works.
Thanks is advance,
Upvotes: 0
Views: 70
Reputation: 288590
You could use:
var values='foo = bar; this = is; not = necessary'.split('; ')[0].split(' = ');
var obj={"name" : values[0], "value" : values[1]}
This way you do:
'foo = bar; this = is; not = necessary'.split('; ')
, which returns ['foo = bar','this = is','not = necessary']
'foo = bar; this = is; not = necessary'.split(';')[0]
gives 'foo = bar'
'foo = bar; this = is; not = necessary'.split(';')[0].split(' = ')
, which gives ['foo','bar']
Upvotes: 3
Reputation: 253456
An approach that uses regular expressions to search in a particular string, for a specified name, which will match the foo = bar
portion of the string:
function getNameValuePair(string, needle) {
if (!string || !needle) {
return false;
}
else {
var newNeedle = needle + '\\s+\\=\\s+\\w+',
expr = new RegExp(newNeedle),
parsed = string.match(expr).join(),
parts = parsed.split(/\s+\=\s+/),
returnObj = {'name' : parts[0], 'value' : parts[1]};
return returnObj;
}
}
var string = 'foo = bar; this = is; not = necessary',
nameValueObj = getNameValuePair(string, 'foo');
console.log(nameValueObj);
This could, of course, be adapted to more suit your requirements.
As it is, however:
false
.needle
('foo' in this case), followed by one, or more, units of white-space followed by a single =
character, followed by one, or more, white-space characters. If the white-space may not always be present, it might be better to change to newNeedle = needle + '\\s*\\=\\s*\\w+'
(the +
matches 'one-or-more', the *
matches 'zero-or-more').parsed
variable,parsed
variable with another regular expression, effectively splitting on a pattern of zero-or-more white-space followed by an =
followed by zero-or-more white-space, storing the separated parts in the parts
array variable,parts
variable.Updated the above, slightly, because two lines to create one RegExp was just silly:
function getNameValuePair(string, needle) {
if (!string || !needle) {
return false;
}
else {
var expr = new RegExp(needle + '\\s+\\=\\s+\\w+'),
parsed = string.match(expr).join(),
parts = parsed.split(/\s+\=\s+/),
returnObj = {'name' : parts[0], 'value' : parts[1]};
return returnObj;
}
}
var string = 'foo = bar; this = is; not = necessary',
nameValueObj = getNameValuePair(string, 'foo');
console.log(nameValueObj);
References:
Upvotes: 1