Extract a value from json inside json string - javascript

var a = '{"test_cmd": "pybot -args : {\"custom-suite-name\" : \"my-1556\"}}'
b = a.match("\"custom-suite-name\" : \"([a-zA-Z0-9_\"]+)\"")
console.log(b)
I have a json string inside json string.
I like to extract the property custom-suite-name's value using the regex.
Output must be,
my-1556.
But the return value b has no matches/null value.

Don't use a regexp to parse JSON, use JSON.parse.
var obj = JSON.parse(a);
var test_cmd = obj.test_cmd;
var args_json = test_cmd.replace('pybot -args : ', '');
var args = JSON.parse(args_json);
var custom_suite = args.custom_suite_name;

It's better to put your regex within / slashes. NOte that,
There is a space exists before colon.
No need to escape double quotes.
Include - inside the character class because your value part contain hyphen also.
Code:
> a.match(/"custom-suite-name" : "([a-zA-Z0-9_-]+)"/)[1]
'my-1556'
> a.match(/"custom-suite-name"\s*:\s*"([a-zA-Z0-9_-]+)"/)[1]
'my-1556'

Related

Using RegExp to substring a string at the position of a special character

Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);

Data Replace is not working

var data = this.state.registerMobile;
//My data will be like +91 345 45-567
data.replace('-','');
It is not removing '-' and i am trying to remove spaces also in between.It's not working.
For that, you need to assign the result of replace to some variable, replace will not do the changes in same variable, it will return the modified value. So use it like this:
var data = this.state.registerMobile;
data = data.replace('-', '');
console.log('updated data', data);
Check the example:
a = '+91 12345678';
b = a.replace('+', '');
console.log('a', a );
console.log('b', b );
String.prototype.replace() does not change the original string but returns a new one. Its first argument is either of the following:
regexp (pattern)
A RegExp object or literal. The match or matches are replaced with newSubStr or the value returned by the specified function.
substr (pattern)
A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.
So if you want to replace hypens and whitespaces, you have to use the following:
var data = this.state.registerMobile;
data = data.replace(/\s|-/g, '');

From string to an Object with Javascript

How can I convert this string: "{one=1,two=2}" into an object with JavaScript? So I can access the values.
I tried replacing the "=" for ":", but then while accessing the object I receive an "undefined". Here is my code:
var numbers = "{one=1,two=2}"; //This is how I receive the string
numbers = numbers.replace(/=/g, ':'); //I use the '/g' to replace all the ocurrencies
document.write(numbers.one); //prints undefined
So this is the string
var str = '{one=1,two=2}';
replace = character to : and also make this as a valid JSON object (needs keys with double-quotes around)
var str_for_json = str.replace(/(\w+)=/g, '"$1"=').replace(/=/g, ':');
In regex, \w means [a-zA-Z0-9_] and the ( ) capture what's inside, usable later like here with $1
Now parse your string to JSON in order to use like that
var str_json = JSON.parse(str_for_json);
Now enjoy. Cheers!!
document.write(str_json.one);
FINALLY :
var str = '{one=1,two=2}';
var str_for_json = str.replace(/(\w+)=/g, '"$1"=').replace(/=/g, ':');
try {
var str_json = JSON.parse(str_for_json);
document.write(str_json.one);
} catch(e) {
console.log("Not valid JSON:" + e);
};
Instead of trying to use regexp to create JSON, I would simply parse the string directly, as in
const result = {};
numbers.match(/{(.*?)}/)[1] // get what's between curlies
.split(',') // split apart key/value pairs
.map(pair => pair.split('=')) // split pairs into key and value
.forEach(([key, value]) => // for each key and value
result[key] = value); // set it in the object
1 - a valide JSON is :var numbers = "{\"one\"=1,\"two\"=2}"; (you need the \")
2- you need to JSON.parse the strign
So this works:
var numbers = "{\"one\"=1,\"two\"=2}"; //This is how I receive the string
numbers = numbers.replace(/=/g, ':'); //I use the '/g' to replace all the ocurrencies
numbers=JSON.parse(numbers);
document.write(numbers.one); //prints undefined
But, it's bad practice !

split words,numbers from string and put it as 2D array in JavaScript

I have an string like'[[br,1,4,12],[f,3]]'. I want to split as strings and integers and put it into array like the string [['br',1,4,12],[f,3]].string maybe like '[]' or '[[cl,2]]',ect...but the words only,br,cl,fand i. How does get the array. Any idea for this problem?
Thanks
You can do conversion that you wanted by using RegEx :
Get your string
var str = '[[br,1,4,12],[f,3]]';
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
console.log(str);
//Outputs :
[["brd",1,4,12],["f",3]] // It is still just a string
If you wanted to convert it to object, you might use this :
var str = '[[br,1,4,12],[f,3]]';
function toJSObject(str){
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
return (JSON.parse(str))
}
var obj = toJSObject(str);

How do I split this string with JavaScript?

Javascript:
var string = '(37.961523, -79.40918)';
//remove brackets: replace or regex? + remove whitespaces
array = string.split(',');
var split_1 = array[0];
var split_2 = array[1];
Output:
var split_1 = '37.961523';
var split_2 = '-79.40918';
Should I just use string.replace('(', '').replace(')', '').replace(/\s/g, ''); or RegEx?
Use
string.slice(1, -1).split(", ");
You can use a regex to extract both numbers at once.
var string = '(37.961523, -79.40918)';
var matches = string.match(/-?\d*\.\d*/g);
You would probably like to use regular expressions in a case like this:
str.match(/-?\d+(\.\d+)?/g); // [ '37.961523', '-79.40918' ]
EDIT Fixed to address issue pointed out in comment below
Here is another approach:
If the () were [] you would have valid JSON. So what you could do is either change the code that is generating the coordinates to produce [] instead of (), or replace them with:
str = str.replace('(', '[').replace(')', ']')
Then you can use JSON.parse (also available as external library) to create an array containing these coordinates, already parsed as numbers:
var coordinates = JSON.parse(str);

Categories