Remove everything outside of the brackets Regex

Viewed 2824

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?

6 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"));

I presume okok.. is a string

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

console.log(d.slice(d.indexOf('{'), d.lastIndexOf('}') + 1))

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

console.log(s);

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);

Just use this code - it splits the item into an array, and removes the first element:

var news = myl.toString().split("{").shift().unshift("{").join("");

You could instead capture it:

var myString = 'okok {"msg":"uc_okok"} bla bla bla';
var myRegexp = /({[^{}]*})/g;
var match = myRegexp.exec(myString);
console.log(match[1]);

This could be put in a loop (while...) but won't work for nested brackets:

var myString = 'okok {"msg":"uc_okok"} bla bla bla {"msg":"uc_okok212121"} lorem ipsum';
var myRegexp = /({[^{}]*})/g;
var match = myRegexp.exec(myString);

while(match !== null) {
    console.log(match[1]);
    match = myRegexp.exec(myString);
}

Related