I'm trying to replace strings with variables in the same way that Python string formatting works.
The string will be in a similar format to:
string = 'Replace $name$ as well as $age$ and $country$';
And I'd like to have a regex operation that will return and array:
['name', 'age', 'country'] or ['$name$', '$age$', '$country$']
So that I can map it to object keys:
{
name : 'Bob',
age : 50,
country : 'US'
}
I've seen solutions using string concatenation but I need a solution using regex because
I have to rely on strings containing these variables.
You can do this:
var string = 'Replace $name$ as well as $age$ and $country$';
var arr = [];
string.replace(/\$(.+?)\$/g, function(m,g1){ arr.push(g1); return m; });
console.log(arr); // desired output
Related
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 have an array of objects which is a string.
[{
'version_name': '1.4',
'url': 'url'
},
{
'version_name': '1.3',
'url': 'url'
},
{
'version_name': '1.2',
'url': 'url'
},
{
'version_name': '1.1',
'url': 'url'
}]
I am using this code to remove all the space:
str = str.replace(/\s+/g, '');
Now, I want to convert it to proper array of objects. How do i do that?
I tried string.split() which kind of works but each array element becomes a string instead of an object.
If you control the source of the string, the best thing would be to modify the source so that it creates valid JSON (" instead of ' on property keys and strings).
If you can't change the source of it and have to deal with that string, you have a couple of options:
Replace the ' with " and use JSON.parse, since that text is valid JSON other than that it uses ' instead of " and it doesn't appear to use ' for anything else:
var result = JSON.parse(theText.replace(/'/g, '"'));
Live Example:
var theText = "[{'version_name':'1.1','url':'value'}, {'version_name':'1.2','url':'value'}, {'version_name':'1.32','url':'value'}, {'version_name':'1.4','url':'value'}]";
var result = JSON.parse(theText.replace(/'/g, '"'));
console.log(result);
Your other option, if you trust the source of that text, is to use eval, since the quoted text is valid JavaScript object initializer syntax.
// ONLY IF YOU CAN ABSOLUTELY TRUST THE SOURCE OF THAT TEXT
var result = eval(theText);
Live Example:
var theText = "[{'version_name':'1.1','url':'value'}, {'version_name':'1.2','url':'value'}, {'version_name':'1.32','url':'value'}, {'version_name':'1.4','url':'value'}]";
var result = eval(theText);
console.log(result);
A JSON string expects key and value to be wrapped in double quotes and not in single. But replacing every single quote can be incorrect as it can be a part of value. So you can pass string through series of regex to make it in correct format.
Sample:
var str = "[{'invalid_value': 'foo's','version_name': '1.4','url': 'url'} , {'version_name': '1.3','url': 'url'},{'version_name': '1.2','url': 'url'},{'version_name': '1.1','url': 'url' }]";
function parseObj(str) {
str = str.replace(/\'\s*:\s*\'/g, '":"');
str = str.replace(/\'\s*,\s*'/g, '","');
str = str.replace(/{\s*\'/g, '{"');
str = str.replace(/\'\s*}/g, '"\}');
return JSON.parse(str);
}
console.log(parseObj(str))
you can use json parse: const arr = JSON.parse(yourString.replace(/'/g, '"')))
Say I have an array of substrings `['abcd', 'xyz', '091823', '9-+#$_#$*']. How can I use regex to make sure that a given string contains ALL of these?
It sounds like you want to take a dynamic array of search terms and check whether another string contains all of the search terms. I don't think you will find a regex-only solution; you should loop through the terms and check each one individually. Also, if the terms are dynamic you probably don't want to use regex unless you know they don't need sanitization (for example, '9-+#$_#$*' contains special regex characters).
Here is a sample solution:
var terms = ['abcd', 'xyz', '091823', '9-+#$_#$*'];
var tests = {
success: 'abcd 091823 xyz 9-+#$_#$*',
failure: 'abcd 091823 xyz'
}
var testKeys = Object.keys(tests);
for(var test of testKeys){
var pass = true;
for(var term of terms){
if(tests[test].indexOf(term) == -1){
pass = false;
break;
}
}
document.body.innerHTML += `${test}: ${pass}<br>`
}
Talking ES6, you are able to use includes() method without using Regular Expressions:
// When `str` doesn't contain all substrings
var str = 'there is no desired substring here';
result = ['abcd', 'xyz', '091823', '9-+#$_#$*'].every(function(e) {
return str.includes(e);
});
console.log(result);
Try using lookarounds:
/(?=.*abcd)(?=.*xyz)(?=.*091823)(?=.*9-\+#\$_#\$\*)/
For the general case of any array of strings to test:
function containsAll(str, arrayOfStr) {
return new RegExp(arrayOfStr.map(function (s) {
return '(?=.*' + s.replace(/([-\\[\]{}.^$+*()|?])/g, '\\$1') + ')';
}).join('')).test(str);
}
containsAll(str, ['abcd', 'xyz', '091823', '9-+#$_#$*']);
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+)
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];