How to replace all   siblings from JSON string in JavaScript? - javascript

How to replace all " " siblings from JSON string?
{
"Cat": "laps milk",
"Dog": "Woofs at Postman",
"Bird": "Jumps over the river",
"I": "Want to learn Regexp"
}
And btw, advice me please some good article or book from where I could finally learn Regexp :(

If you're parsing the JSON string, you can also use the reviver parameter of JSON.parse(string, [reviver]):
var jsonStr = '{"Cat":"laps milk","Dog":"Woofs at Postman","Bird":"Jumps over the river","I":"Want to learn Regexp"}';
var result = JSON.parse(jsonStr, function (key, value) {
return value.replace(/ /g, " ");
});
Likewise, the stringify method allows a replacer function which will replace any values when converting to a JSON string:
var obj = {"Cat":"laps milk","Dog":"Woofs at Postman","Bird":"Jumps over the river","I":"Want to learn Regexp"};
var result = JSON.stringify(obj, function (key, value) {
return value.replace(/ /g, " ");
});
Of course, this is assuming you're using json2.js or a browser with the correct ECMAScript 5th Edition implementation of the JSON object.

var json = { "Cat" : "laps_ milk",
"Dog" : "Woofs_ at_ Postman",
"Bird" : "Jumps_ over_ the_ river",
"I" : "Want_ to_ learn_ Regexp" };
for (var prop in json) {
json[prop] = json[prop].replace(/_/gi, '');
}
Regular Expressions is a good place to learn regexes.

Try this:
var obj = {"Cat":"laps milk","Dog":"Woofs at Postman","Bird":"Jumps over the river","I":"Want to learn Regexp"};
for(var key in obj) {
obj[key] = obj[key].replace(' ', '');
}
Also, the place that has helped me most in learning regular expressions:
http://www.regular-expressions.info/reference.html

In Mootools: console.log(JSON.encode(mystring).replace(/ /gi, ' '));

Related

How to get value in $1 in regex to a variable for further manipulation [duplicate]

You can backreference like this in JavaScript:
var str = "123 $test 123";
str = str.replace(/(\$)([a-z]+)/gi, "$2");
This would (quite silly) replace "$test" with "test". But imagine I'd like to pass the resulting string of $2 into a function, which returns another value. I tried doing this, but instead of getting the string "test", I get "$2". Is there a way to achieve this?
// Instead of getting "$2" passed into somefunc, I want "test"
// (i.e. the result of the regex)
str = str.replace(/(\$)([a-z]+)/gi, somefunc("$2"));
Like this:
str.replace(regex, function(match, $1, $2, offset, original) { return someFunc($2); })
Pass a function as the second argument to replace:
str = str.replace(/(\$)([a-z]+)/gi, myReplace);
function myReplace(str, group1, group2) {
return "+" + group2 + "+";
}
This capability has been around since Javascript 1.3, according to mozilla.org.
Using ESNext, quite a dummy links replacer but just to show-case how it works :
let text = 'Visit http://lovecats.com/new-posts/ and https://lovedogs.com/best-dogs NOW !';
text = text.replace(/(https?:\/\/[^ ]+)/g, (match, link) => {
// remove ending slash if there is one
link = link.replace(/\/?$/, '');
return `${link.substr(link.lastIndexOf('/') +1)}`;
});
document.body.innerHTML = text;
Note: Previous answer was missing some code. It's now fixed + example.
I needed something a bit more flexible for a regex replace to decode the unicode in my incoming JSON data:
var text = "some string with an encoded 's' in it";
text.replace(/&#(\d+);/g, function() {
return String.fromCharCode(arguments[1]);
});
// "some string with an encoded 's' in it"
If you would have a variable amount of backreferences then the argument count (and places) are also variable. The MDN Web Docs describe the follwing syntax for sepcifing a function as replacement argument:
function replacer(match[, p1[, p2[, p...]]], offset, string)
For instance, take these regular expressions:
var searches = [
'test([1-3]){1,3}', // 1 backreference
'([Ss]ome) ([A-z]+) chars', // 2 backreferences
'([Mm][a#]ny) ([Mm][0o]r[3e]) ([Ww][0o]rd[5s])' // 3 backreferences
];
for (var i in searches) {
"Some string chars and many m0re w0rds in this test123".replace(
new RegExp(
searches[i]
function(...args) {
var match = args[0];
var backrefs = args.slice(1, args.length - 2);
// will be: ['Some', 'string'], ['many', 'm0re', 'w0rds'], ['123']
var offset = args[args.length - 2];
var string = args[args.length - 1];
}
)
);
}
You can't use 'arguments' variable here because it's of type Arguments and no of type Array so it doesn't have a slice() method.

JS - Have function repeat until condition met

this seems simple but I'm still having difficulty (I'm relatively new).
I have a function replaceNextParameter() which goes through a string and replaces text between two strings I notate as sub1 and sub2. A string may have 0, 1 or many sub1 and sub2 present. I would like it to execute function replaceNextparameter until there are no more sub1 and sub2 present and return the result.
Here is my code:
function findAllParametersInString (string, sub1, sub2, parameterAndInputArray) {
newString = string
if (newString.indexOf(sub1) > -1 && newString.indexOf(sub2) > -1) {
newString = replaceNextParameter(sub1, sub2, newString, parameterAndInputArray);
}
return newString
};
Here is a live example of what it should do.
//data:
const paramsArray = [
{param: "company", input: "COMPANY"},
{param: "url", input: "URL"},
]
const sampleMessage = "BlaBlaBla {{company}} and {{url}}"
findAllParametersInString(sampleMessage,'{{', '}}', paramsArray);
//Should return "BlaBlaBla COMPANY and URL"
Any idea how to fix it? Currently it only returns "BlaBlaBla COMPANY and {{url}}"
I suggest you to use your param value as key, and your input value as value in one single object. Like this:
var params = {
company: "COMPANY",
url: "URL"
};
and now use this simple function:
var sampleMessage = "BlaBlaBla {{company}} and {{url}}";
function replace(str, map) {
for (var key in map) {
str = str.split('{{' + key + '}}').join(map[key]);
}
return str;
}
replace(sampleMessage, params); // -> "BlaBlaBla COMPANY and URL"
You can use parameters for {{ and }} in replace function
Although late, yet I hope this solution might be suitable for someone.
The best solution I think, since it's string you want to deal with, is to use regular expression.
Although I'm not sure what the parameterAndInputArray is for though.
So I would use this (although a better regex can be created):
let newstring = oldstring.replace(/sub1/gi,replacement1).replace(/sub2/gi,replacement2)
where replacement[1/2] will be the character to be replaced eg('#') or empty quotes ('') if sub[1/2] are to be removed.
function findAllParametersInString (string, sub1, sub2, parameterAndInputArray) {
newString = string
while (newString.indexOf(sub1) > -1 && newString.indexOf(sub2) > -1) {
newString = replaceNextParameter(sub1, sub2, newString, parameterAndInputArray);
}
return newString
};
Did the trick based off of #Flemming

Parse string having key=value pairs as JSON

My node app receives a series of strings in the format "a=x b=y c=z" (i.e. a string containing several space-separated key=value pairs).
What is the neatest way of converting such a string into a JSON object of the form {a: x, b: y, c: z}?
I'm betting that there's a one-line solution, but haven't managed to find it yet.
Thanks.
One way would be to replace the with a , and an = with a ::
var jsonStr = '{' + str.replace(/ /g, ', ').replace(/=/g, ': ') + '}';
Or if you need quotes around the keys and values:
var jsonStr2 = '{"' + str.replace(/ /g, '", "').replace(/=/g, '": "') + '"}';
JSON.parse() it if you need.
Sample output:
str: a=x b=y c=z
jsonStr: {a: x, b: y, c: z}
jsonStr2: {"a": "x", "b": "y", "c": "z"}
Building on John Bupit's excellent answer, I have made a couple of further enhancements to end up with the following (the string being parsed being in message):
var json = JSON.parse(('{"' + message.replace(/^\s+|\s+$/g,'').replace(/=(?=\s|$)/g, '="" ').replace(/\s+(?=([^"]*"[^"]*")*[^"]*$)/g, '", "').replace(/=/g, '": "') + '"}').replace(/""/g, '"'));
Basically the scheme is as follows:
First replace(): trim off any leading or trailing whitespace -- equivalent to trim()
Second replace(): add double quotes (empty string) for any value that is completely missing (e.g. key1= key2=val goes to key1="" key2=val).
Third replace(): replace each space (which acts as a delimiter) with ", ", but not where the space is within double quotes (i.e. part of a string value).
Fourth replace(): replace each = with ": "
Wrap the entire string up as follows: {"..."}
Finally, replace any double quotes "" created by the above steps (because the value string was already wrapped in quotes in message) with single quotes "
Even more finally, run JSON.parse() over the result.
The above scheme should cope with missing values, with some values being quoted and some unquoted, and with spaces within value strings, e.g. something like a= b="x" c="y y" d=z.
Assuming that you don't get nested objects in that format :
var sample = 'a=x b=y c=z';
var newobj = {};
sample.split(' ').forEach(function (value) {
var keypair = value.split('=');
newobj[keypair[0]] = keypair[1];
});
console.dir(newobj);
What this does is split on every white-space and push to an array, and the array is looped and each item in array is split again to get each key-value pair which is assigned to the newobj.
Here's a simple function that will do the trick
function stringToObj (string) {
var obj = {};
var stringArray = string.split(' ');
for(var i = 0; i < stringArray.length; i++){
var kvp = stringArray[i].split('=');
if(kvp[1]){
obj[kvp[0]] = kvp[1]
}
}
return obj;
}
newstr = ""
for kvp in #value.split(" ")
newstr += kvp.replace(/=/,'":"').replace(/^/, '"').replace(/$/, '"').replace(/\"\"/,'" "')
newstr = newstr.replace(/\"\"/g, '","')
jsn = JSON.parse('{' + newstr + '}')
I created a simple online tool for similar need: https://superal.github.io/online-tools/
Use cases:
To transfer key:value pairs copied from chrome network requests(form data or query string parameters) or postman headers key-value(in bulk edit style) to json format.
For example:
key:value pairs
platform:2
limit:10
start_time:1521561600
end_time:1522080000
offset:0
to json format
{
"platform": "2",
"limit": "10",
"start_time": "1521561600",
"end_time": "1522080000",
"offset": "0"
}
It can be parsed (converted to json) using the help of this npm athena-struct-parser package.
For more information about the package -- https://www.npmjs.com/package/athena-struct-parser
Sample Nodejs Code
var parseStruct =require('athena-struct-parser') ;
var str = '{description=Check the Primary key count of TXN_EVENT table in Oracle, datastore_order=1, zone=yellow, aggregation_type=count, updatedcount=0, updatedat=[2021-06-09T02:03:20.243Z]}'
var parseObj = parseStruct(str)
console.log(parseObj);
Sample string with key=value format taken
{description=Check the Primary key count of TXN_EVENT table in Oracle, datastore_order=1, zone=yellow, aggregation_type=count, updatedcount=0, updatedat=[2021-06-09T02:03:20.243Z]}
Result Parsed output
{
description: 'Check the Primary key count of TXN_EVENT table in Oracle',
datastore_order: '1',
zone: 'yellow',
aggregation_type: 'count',
updatedcount: '0',
updatedat: [ '2021-06-09T02:03:20.004Z' ]
}
I would use an approach leveraging URLSearchParams and Object.fromEntries() like so:
const input = "a=x b=y c=z";
const queryString = input.replaceAll(" ", "&");
const query = new URLSearchParams(queryString);
const output = Object.fromEntries(query);
console.log(output);
Breakdown:
The URLSearchParams constructor takes a string of key-value pairs joined by "&" as it's argument, and parses it into a URLSearchParams object instance. So to use this, the space separators in the original input need to be replaced with a "&" character.
The URLSearchParams instance we have after parsing is an iterable, so we can transform it into a plain Object with Object.fromEntries().
It's not too bad as a one-liner either:
const input = "a=x b=y c=z";
const output = Object.fromEntries(new URLSearchParams(input.replaceAll(" ", "&")));

replace all commas within a quoted string

is there any way to capture and replace all the commas within a string contained within quotation marks and not any commas outside of it. I'd like to change them to pipes, however this:
/("(.*?)?,(.*?)")/gm
is only getting the first instance:
JSBIN
If callbacks are okay, you can go for something like this:
var str = '"test, test2, & test3",1324,,,,http://www.asdf.com';
var result = str.replace(/"[^"]+"/g, function (match) {
return match.replace(/,/g, '|');
});
console.log(result);
//"test| test2| & test3",1324,,,,http://www.asdf.com
This is very convoluted compared to regular expression version, however, I wanted to do this if just for the sake of experiment:
var PEG = require("pegjs");
var parser = PEG.buildParser(
["start = seq",
"delimited = d:[^,\"]* { return d; }",
"quoted = q:[^\"]* { return q; }",
"quote = q:[\"] { return q; }",
"comma = c:[,] { return ''; }",
"dseq = delimited comma dseq / delimited",
"string = quote dseq quote",
"seq = quoted string seq / quoted quote? quoted?"].join("\n")
);
function flatten(array) {
return (array instanceof Array) ?
[].concat.apply([], array.map(flatten)) :
array;
}
flatten(parser.parse('foo "bar,bur,ber" baz "bbbr" "blerh')).join("");
// 'foo "barburber" baz "bbbr" "blerh'
I don't advise you to do this in this particular case, but maybe it will create some interest :)
PS. pegjs can be found here: (I'm not an author and have no affiliation, I simply like PEG) http://pegjs.majda.cz/documentation

Javascript regular expression help needed

I have a string:
User_TimeStamp=20120712201112&email_id=ufe.test20#markit.com&resetCode=**uNcoHR9O3wAAB46xw**&reset=true
I tried and Googled a lot to get the highlighted text. Basically I want a JavaScript regex to get all characters in between resetCode= and &reset=true.
Any help regarding this is highly appreciated.
Thanks
Try this code where you're looking for the resetCode variable
var resetCodeValue;
var s = window.location.split('&');
for(var k in s) { var pair = s[k].split('=');
if (pair[0] == 'resetCode'){
resetCodeValue = pair[1];
}
}
Two ways:
Your regex should be resetCode=([^&]*)
Split the string on & then iterate through each string and split on = comparing the first string to resetCode and return the second string when you find it.
You can do something more 'readable':
retrieveDesired = User_TimeStamp.split('=')[3].split('&')[0];
jsBin demo
why not just use this handy function to get the value of resetCode
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
document.write(getUrlVars()["resetCode"]);

Categories

Resources