Json from string using regular expression - javascript

I have a string like:
const stringVar = ":20:9077f1722efa3632 :12:700 :77E: :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
I want to create JSON from above stringVar:
{
":21:" : "9077f1722efa3632",
":12:" : "700",
":27A:": "2/2",
":21A:": "9077f1722efa3632",
":27:" : "1/2",
":40A:": "IRREVOCABLE"
}
So, I was thinking I could split with regular expression (":(any Of char/digit):")
I would make the first part the key and the second part its value.

The regular expression /(:\w+:)(\S+)/ matches the whole key:value pair. You can add the g modifier, and then use it in a loop to get all the matches and put them into the object.
const stringVar = ":20:9077f1722efa3632 :12:700 :77E: :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
var regexp = /(:\w+:)(\S+)/g;
var obj = {};
var match;
while (match = regexp.exec(stringVar)) {
obj[match[1]] = match[2];
}
console.log(obj);
If you want to create an array of {key: ":20:", value: "9077f1722efa3632"}, you can modify the code to:
const stringVar = ":20:9077f1722efa3632 :12:700 :77E: :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
var regexp = /(:\w+:)(\S+)/g;
var array = [];
var match;
while (match = regexp.exec(stringVar)) {
array.push({key: match[1], value: match[2]});
}
console.log(array);
If the values can contain space, change the regexp to:
/(:\w+:)([^:]+)\s/g
This will match anything not containing : as the value, but not include the last space.

You can achieve the same result without using regex.
const stringVar = ":20:9077f1722efa3632 :12:700 :77E:xxx :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE";
const result = stringVar
.split(' ')
.reduce((ret, current) => {
const pos = current.indexOf(':', 1);
ret[current.substring(0, pos + 1)] = current.substring(pos + 1);
return ret;
}, {});
console.log(result);

Related

How to extract specific words from a string with some patterns?

I am trying to extract some strings from a word with some pattern like -
"38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"
how will I extract all word between - separately, means first word before - and then second word between - and - and so on...
string = "38384-1-page1-2222";
string.substr(0, string.indexof("-")); //return 38384
But how will I extract 1, page1 and 2222 all the words separately?
The javascript function str.split(separator) split the string by the given separator and it returns an array of all the splited string. REF Here
Here is an example following your question :
var string = "38384-1-page1-2222";
var separator = "-";
var separated = string.split(separator);
var firstString = separated[0]; // will be '38384'
var secondString = separated[1]; // will be '1'
var thirdString = separated[2]; // will be 'page1'
/* And So on ... */
Hope this can help
Use String.prototype.split() to get your string into array
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var resultArray = [];
for (let i = 0; i < words.length;i++) {
let temp = words[i];
resultArray = pushArray(temp.split("-"), resultArray)
}
console.log(resultArray)
function pushArray (inputArray, output) {
for (let i = 0; i < inputArray.length;i++) {
output.push(inputArray[i]);
}
return output;
}
Or simply use Array.prototype.reduce()
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var result = words.reduce((previousValue, currentValue) => previousValue.concat(currentValue.split("-")), [])
console.log(result)
You can use regex /[^-]+/g
const words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
console.log(words.map(v=>v.match(/[^-]+/g)).flat())

Extracting Key:Value pairs assoc with regex from string on Javascript

I have the following string
server:all, nit:4545, search:dql has map
with the regular expression /(\w+):((?:"[^"]*"|[^:,])*)/g I get
["server:all", "nit:4545", "search:dql has map"] //Array
But I want to get
{server:"all","nit":"4545","search":"dql has map"}
OR
[{server:"all"},{"nit":"4545"},{"search":"dql has map"}]
You can use a simple regex for key:value and use a look using exec:
var str = 'server:all, nit:4545, search:dql has map';
var re = /([\w-]+):([^,]+)/g;
var m;
var map = {};
while ((m = re.exec(str)) != null) {
map[m[1]] = m[2];
}
console.log(map);
You can use String#replace to loop over the matches and captures and assign those to an empty object.
const string = 'server:all, nit:4545, search:dql has map';
const regex = /(\w+):((?:"[^"]*"|[^:,])*)/g;
const map = {};
string.replace(regex, (m, c1, c2) => {
map[c1] = c2;
});
console.log(map);
For your example data, you could also first split on a comma and then split on a colon:
let str = "server:all, nit:4545, search:dql has map";
let result = {};
str.split(',').forEach(function(elm) {
[k, v] = elm.trim().split(':');
result[k] = v;
});
console.log(result);

regex to find pairs in array

I would like to parse that string:
[[abc.d.2,mcnv.3.we],[abec.d.2,mcnv.4.we],[abhc.d.2,mcnv.5.we]]
In order to have a key value (JSON)
{
"abc.d.2": "mcnv.3.we",
"abec.d.2: "mcnv.4.we",
"abhc.d.2": "mcnv.5.we"
}
First I would like to check if string can be parse to make it key=>value.
How can I check the string if it contains pairs?
Thanks
You can try something like this:
Approach 1:
Idea:
Update the regex to have more specific characters. In your case, alphanumeric and period.
Get all matching elements from string.
All odd values are keys and even matches are values.
Loop over matches and create an object.
const str = "[[abc.d.2,mcnv.3.we],[abec.d.2,mcnv.4.we],[abhc.d.2,mcnv.5.we]]";
const matches = str.match(/[\w\.\d]+/gi);
const output = {};
for(var i = 0; i< matches.length; i+=2) {
output[matches[i]] = matches[i+1];
}
console.log(output)
Approach 2:
Idea:
Write a regex to capture each individual group: [...:...]
Then eliminate braces [ and ].
Split string using comma ,.
First part is your key. Second is your value.
const str = "[[abc.d.2,mcnv.3.we],[abec.d.2,mcnv.4.we],[abhc.d.2,mcnv.5.we]]";
const matches = str.match(/\[([\w\d\.,]*)\]/gi);
const output = matches.reduce((obj, match) => {
const parts = match.substring(1, match.length - 1).split(',');
obj[parts[0]] = parts[1];
return obj;
}, {})
console.log(output)
In above approach, you can also include Map. The iteration can be bit confusing initially, but you can try.
const str = "[[abc.d.2,mcnv.3.we],[abec.d.2,mcnv.4.we],[abhc.d.2,mcnv.5.we]]";
const matches = str.match(/\[([\w\d\.,]*)\]/gi);
const output = matches.reduce((obj, match) => {
const parts = match.substring(1, match.length - 1).split(',');
obj.set(...parts)
return obj;
}, new Map())
for (const [k, v] of output.entries()) {
console.log(`Key: ${k}, value: ${v}`)
}
Parse the array as JSON, iterate over the array, adding entries to the target object as you go, watch out for duplicate keys:
let dict_target = {}; // The target dictionary,
let src, arysrc, proceed = false;
try {
src = "[[abc.d.2,mcnv.3.we],[abec.d.2,mcnv.4.we],[abhc.d.2,mcnv.5.we]]"
.replace(/,/g, '","')
.replace(/\]","\[/g, '"],["')
.replace(/^\[\[/, '[["')
.replace(/\]\]$/, '"]]')
;
arysrc = JSON.parse(src);
proceed = true; // Could parse the data, can carry on with processing the data
} catch (e) {
console.log(`Source data unparseable, error '${e.message}'.`);
}
if (proceed) {
arysrc.forEach ( (a_item, n_idx) => {
if (dict_target.hasOwnProperty(a_item[0])) {
// add any tests and processing for duplicate keys/value pairs here
if (typeof dict_target[a_item[0]] === "string") {
dict_target[a_item[0]] = [ dict_target[a_item[0]] ];
}
dict_target[a_item[0]].push(a_item[1]);
}
else {
dict_target[a_item[0]] = a_item[1];
}
});
} // if -- proceed
My coding golf solution...
const parse = (str) => {
let obj = {};
str.replace(
/\[([^\[,]+),([^\],]+)\]/g,
(m, k, v) => obj[k] = v
);
return obj;
};
Advantages:
More Permissive of arbitrary chars
More Tolerant of missing values
Avoids disposable objects for GC
Disadvantages:
More Permissive of arbitrary chars!
This is not a proper parser...
Does not have context, just [key,val]
I actually wanted to post the following as my answer... but I think it'll get me in trouble :P
const parse=(str,obj={})=>
!str.replace(/\[([^\[,]+),([^\],]+)\]/g,(m,k,v)=>obj[k]=v)||obj;
Here's the code which validates the string first and outputs the result. Not at all optimal but does the task just fine.
var string = '[[abc.d.2,mcnv.3.we],[abec.d.2,mcnv.4.we],[abhc.d.2,mcnv.5.we]]';
var result = (/^\[(\[.*\..*\..*\,.*\..*\..*\]\,)*\[(.*\..*\..*\,.*\..*\..*)\]\]$/g).exec(string);
if (result) {
var r1 = result[1].replace(/\[|\]/g, '').split(',');
var r2 = result[2].split(',');
var output = {};
for (var i = 0; i < r1.length -1; i +=2) {
output[r1[i]] = r1[i+1];
}
output[r2[0]] = r2[1];
console.log(output);
} else {
console.log('invalid string');
}

Javascript search replace string from array

I am new in javascript. I want to replace string value from array if array key value match with string value
Here is my following code:
var arr= [];
arr[11] = 'XYZ';
arr[12] = 'ABC';
var string = "11-12";
My Output will be :
var str ="XYZ-ABC";
Use String#replace method with a callback.
var arr = [];
arr[11] = 'XYZ';
arr[12] = 'ABC';
var string = "11 - 12";
// match all digits in string and replace it with
// corresponding value in `arr`
var res = string.replace(/\d+/g, function(m) {
return arr[m];
})
console.log(res);
You can use regx.test() to get the Boolean value to check if it is character or not .
var arr = [];
arr[11] = 'XYZ';
arr[12] = 'ABC';
if(/[a-zA-Z\s]+/.test(arr[11])&&/[a-zA-Z\s]+/.test(arr[12])){
var str=arr[11]+ " " +arr[12];
}
You just need array methods (split map and join), neither regex nor jquery:
var str = string.split("-").map(elem => arr[elem]).join("-");

Replace last comma separated value by another using regex

I have a string as follows :
var str = "a,b,c,a,e,f";
What I need is replace the last comma separated element by another.
ie, str = "a,b,c,a,e,anystring";
I have done it using split method and adding it to make a new string. But it is not working as expected
What I done as follows :
var str = "a,b,c,d,e,f";
var arr = str.split(',');
var res = str.replace(arr[5], "z");
alert(res);
Is there any regex to help?
You can use replace() with regex /,[^,]+$/ to match the last string
var str = "a,b,c,d,e,old";
var res = str.replace(/,[^,]+$/, ",new");
// or you can just use
// var res = str.replace(/[^,]+$/, "new");
document.write(res);
Or you can just use regex str.replace(/[^,]+$/, "new");
var str = "a,b,c,d,e,old";
var res = str.replace(/[^,]+$/, "new");
document.write(res);
Or using split() , replace the last array value with new string and then join it again using join() method
var str = "a,b,c,d,e,old";
var arr = str.split(',');
arr[arr.length - 1] = 'new';
var res = arr.join(',');
document.write(res);
You could just use a String.substring() of String.lastIndexOf():
function replaceStartingAtLastComma(str, rep){
return str.substring(0, (str.lastIndexOf(',')+1))+rep;
}
console.log(replaceStartingAtLastComma('a,b,c,d,e,f', 'Now this is f'));

Categories

Resources