I have example string:
[:pl]Field_value_in_PL[:en]Field_value_in_EN[:]
And I want get something like it:
Object {
pl: "Field_value_in_PL",
en: "Field_value_in_EN"
}
But I cannot assume there will be always "[:pl]" and "[:en]" in input string. There can by only :pl or :en, :de and :fr or any other combination.
I tried to write Regexp for this but I failed.
Try using .match() with RegExp /:(\w{2})/g to match : followed by two alphanumeric characters, .map() to iterate results returned from .match(), String.prototype.slice() to remove : from results, .split() with RegExp /\[:\w{2}\]|\[:\]|:\w{2}/ to remove [, ] characters and matched : followed by two alphanumeric characters, .filter() with Boolean as parameter to remove empty string from array returned by .split(), use index of .map() to set value of object, return object
var str = "[:pl]Field_value_in_PL[:en]Field_value_in_EN[:]:deField_value_in_DE";
var props = str.match(/:(\w{2})/g).map(function(val, index) {
var obj = {}
, prop = val.slice(1)
,vals = str.split(/\[:\w{2}\]|\[:\]|:\w{2}/).filter(Boolean);
obj[prop] = vals[index];
return obj
});
console.log(JSON.stringify(props, null, 2))
Solution with String.replace , String.split and Array.forEach functions:
var str = "[:pl]Field_value_in_PL[:en]Field_value_in_EN[:fr]Field_value_in_FR[:de]Field_value_in_DE[:]",
obj = {},
fragment = "";
var matches = str.replace(/\[:(\w+?)\]([a-zA-Z_]+)/gi, "$1/$2|").split('|');
matches.forEach(function(v){ // iterating through key/value pairs
fragment = v.split("/");
if (fragment.length == 2) obj[fragment[0]] = fragment[1]; // making sure that we have a proper 'final' key/value pair
});
console.log(obj);
// the output:
Object { pl: "Field_value_in_PL", en: "Field_value_in_EN", fr: "Field_value_in_FR", de: "Field_value_in_DE" }
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
You can try this regex to capture in one group what's inside a pair of brackets and in the other group the group of words that follow the brackets.
(\[.*?\])(\w+)
Related
I have such a string "Categ=All&Search=Jucs&Kin=LUU".How to get an array of values from this line [All,Jucs,LUU].
Here is an example
let x = /(\b\w+)$|(\b\w+)\b&/g;
let y = "Categories=All&Search=Filus";
console.log(y.match(x));
but I wanted no character &.
Since this looks like a URL query string, you can treat it as one and parse the data without needing a regex.
let query = "Categ=All&Search=Jucs&Kin=LUU",
parser = new URLSearchParams(query),
values = [];
parser.forEach(function(v, k){
values.push(v);
});
console.log(values);
Docs: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
Note: This may not work in IE, if that's something you care about.
Loop through all matches and take only the first group, ignoring the =
let x = /=([^&]+)/g;
let y = "Categories=All&Search=Filus";
let match;
while (match = x.exec(y)) {
console.log(match[1]);
}
To achieve expected result, use below option of using split and filter with index to separate Keys and values
1. Use split([^A-Za-z0-9]) to split string based on any special character other letters and numbers
2. Use Filter and index to get even or odd elements of array for keys and values
var str1 = "Categ=All&Search=Jucs&Kin=LUU";
function splitter(str, index){
return str.split(/[^A-Za-z0-9]/).filter((v,i)=>i%2=== index);
}
console.log(splitter(str1, 0)) //["Categ", "Search", "Kin"]
console.log(splitter(str1, 1))//["All", "Jucs", "LUU"]
codepen - https://codepen.io/nagasai/pen/yWMYwz?editors=1010
What would be the best way to split an a string that a declaration of an array into an array of strings using javascript/jquery. An example of a string I am working with:
franchise[location][1][location_name]
I would like it to be converted into an array like:
['franchise', 'location', '1', 'location_name']
BONUS: If I could also get that numeric value to be an integer and not just a string in one fell swoop, that would be terrific.
You can use String.split with a regex that matches all the none alpha numeric chars.
Something like that:
const str = 'franchise[location][1][location_name]';
const result = str.split(/\W+/).filter(Boolean);
console.log(result);
One option would be to just match word characters:
console.log(
'franchise[location][1][location_name]'.match(/\w+/g)
);
To transform the "1" to a number, you might .map afterwards:
const initArr = 'franchise[location][1][location_name]'.match(/\w+/g);
console.log(initArr.map(item => !isNaN(item) ? Number(item) : item));
You could try
const str = 'franchise[location][1][location_name]';
const res = str.split(/\W+/).map(i => { return Number(i) ? Number(i) : i;})
I would like to capture the array key from a string.
Here are my words: message[0][generic][0][elements][0][default_action][url]...
I want to capture the array keys after message[0][generic][0][elements][0], and the expected results are default_action and url etc.
I have tried following patterns but not work.
message\[0\]\[generic\]\[0\]\[elements\]\[0\](?=\[(\w+)\]): it captures default_action only;
\[(\w+)\]: it captures all array keys, but includes 0, generic, elements...
Is there any regex pattern for JavaScript that make the result array inverse, like [url, default_action]?
You can replace unwanted part of a string,and then get all other keys.
var string = 'message[0][generic][0][elements][0][default_action][url][imthird]';
var regexp = /message\[0\]\[generic\]\[0\]\[elements\]\[0\]/
var answer = string.replace(regexp,'').match(/[^\[\]]+/g)
console.log(answer);
To extract any number of keys and reverse the order of the elements in resulting array:
str = "message[0][generic][0][elements][0][default_action][url]";
res = str.match(/\[([^\d\]]+)\](?=\[[^\d\]]*\]|$)/g)
.map(function(s) { return s.replace(/[\[\]]/g, "") })
.reverse();
console.log(res);
The solution using String.prototype.split() and Array.prototype.slice() functions:
var s = 'message[0][generic][0][elements][0][default_action][url]...',
result = s.split(/\]\[|[\[\]]/g).slice(-3,-1);
console.log(result);
Using Javascript / jQuery, I have the following string;
MasterString = "typography,caret,car,card,align,shopping-cart,adjust,allineate";
What's the best RegEx for extracting all the words that contains e.g. "car", so I have the following string left;
ResultString = "caret,car,card,shopping-cart";
And is it also possible to extract only the first word, that contains "car"?
ResultString = "caret";
I am writing a simple search-routine, which matches the query (car) against a comma seperated list and I want to show the first result as the outcome for the query.
UPDATE
I tried the simple RegEx mentioned in the answer below;
[^,]*car[^,]*
It works perfect, see this (test-)image - http://i.imgur.com/RXwkrrF.png?1
The query is "car" and all icons tagged with a word that contains at least "car" are made visible in the search-results.
The only problem is that the search-string "car" is always different (depends on user input in the search-form). So how can I enter a variable match-string in the RegEx above?
Something like this;
[^,]*%QUERY-FROM-SEARCHFIELD%[^,]*
You could try the below regex to match only the strings caret,car,card,shopping-cart,
[^,]*car[^,]*
DEMO
> var masterString = "typography,caret,car,card,align,shopping-cart,adjust,allineate";
undefined
> masterString.match(/[^,]*car[^,]*/g);
[ 'caret',
'car',
'card',
'shopping-cart' ]
To match the first word which contains the string car, you need to remove the global flag from the pattern.
> masterString.match(/[^,]*car[^,]*/);
[ 'caret',
index: 11,
input: 'typography,caret,car,card,align,shopping-cart,adjust,allineate' ]
Now convert the array into a string delimited by comma and stored it into a variable.
> var resultString = masterString.match(/[^,]*car[^,]*/g).join(",");
undefined
> resultString
'caret,car,card,shopping-cart'
You can do so without regex:
Split the string to an array:
var tempArray = MasterString.split( ',' );
Filter the array for values which contain the word car in it:
tempArray = tempArray.filter(function (x) {
if (x.contains('car')) return x;
});
Join the resulting array back:
ResultString = tempArray.join( ',' );
MasterString = "typography,caret,car,card,align,shopping-cart,adjust,allineate";
var tempArray = MasterString.split( ',' );
tempArray = tempArray.filter(function (x) {
if (x.contains('car')) return x;
});
ResultString = tempArray.join( ',' );
To get the first result, simply access the 0th element of tempArray:
var x = tempArray[0];
but not an empty string?
// loop through space separated "tokens" in a string
// will loop through "" - needs update
$P.eachString = function (str, func, con) {
var regexp = /^|\s+/;
if (regexp.test(str)) {
// ... stuff
}
};
The code above will match "" the empty string. I want to match against
case1
some_string
case2
some_string1 some_string2
case3
some_string1 some_string2 some_string_3
etc.
Just use String.split and iterate over the returned array:
Splits a String object into an array of strings by separating the string into substrings.
If separator is omitted, the array contains one element consisting of the entire string.