Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove everything outside of the brackets Regex

This is what I am trying to remove strings from:

var myl = 'okok{"msg":"uc_okok"}'

and the results should be:

{"msg":"uc_okok"}

I have tried using regex

var news = myl.toString().replace(/ \{(.*""?)\}/g);

but it's not working? Any ideas?

like image 927
MR_AMDEV Avatar asked Nov 13 '18 07:11

MR_AMDEV


4 Answers

How about using the following;

myl.toString().replace(/.*?({.*}).*/, "$1")

It should work with multiple layers of brackets as well;

str = 'okok{"msg":"uc_okok"}';
console.log(str.replace(/.*?({.*}).*/, "$1"));

str = 'adgadga{"okok":{"msg":"uc_okok"}}adfagad';
console.log(str.replace(/.*?({.*}).*/, "$1"));
like image 154
buræquete Avatar answered Oct 19 '22 22:10

buræquete


Also you can simply extract the string between brackets as below;

var myl = "okok{\"msg\":\"uc_okok\"}okok";
var mylExtractedStr = myl.match('\{.*\}')[0];

console.log(mylExtractedStr);
like image 22
Erdem Savasci Avatar answered Oct 20 '22 00:10

Erdem Savasci


I presume okok.. is a string

var d = 'okok{"msg":"uc_okok"}'

console.log(d.slice(d.indexOf('{'), d.lastIndexOf('}') + 1))
like image 36
Nitish Narang Avatar answered Oct 19 '22 22:10

Nitish Narang


s = 'okok{"msg":"uc_okok"}';
s = '{' + s.split('{')[1].split('}')[0] + '}';

console.log(s);
like image 31
Harun Or Rashid Avatar answered Oct 19 '22 22:10

Harun Or Rashid