最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove everything outside of the brackets Regex - Stack Overflow

programmeradmin9浏览0评论

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?

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?

Share Improve this question edited Nov 13, 2018 at 8:52 Jack Bashford 44.1k11 gold badges55 silver badges82 bronze badges asked Nov 13, 2018 at 7:04 MR_AMDEVMR_AMDEV 1,9422 gold badges23 silver badges40 bronze badges 0
Add a ment  | 

6 Answers 6

Reset to default 13

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

发布评论

评论列表(0)

  1. 暂无评论