Tag:javascript正则表达式
Article From:https://segmentfault.com/q/1010000012147179
Question:
var obj1 = {
    "name": "",
    "children": [
        {
            "name": "The first sentence ","Content": "1","Children": [{"NAme ":" the subnode of the first sentence ","Content": "1children","Children": []}]},{"Name": "the second sentence","Content": "2","Children": [{"Name": "The subnode of the two sentence ""Content": "2children","Children": [{"Name": "the child node of the second sentence","Content":" 2children2children ","Children": []}]}]}]}VarObj2 = {{"Name": "the child of the first sentence","Content": "1children","Children": []};Var patt = new RegEXP (JSON.stringify (obj2),'g');Var newData = JSON.stringify (obj1).Replace (patt,'1111111111111');ConSole.log (newData);

Why there is no way of the code aboveobj1Cut off in the middleobj2What about this section?
The result of the output is complete.obj1,As if nothing had been done

Answer 0:

Open the developer tool, andpattPrint it out and you’ll find that,pattAs follows:

We know[]There are special meanings in regular expressions, which represent character sets and match them.[]Any character in it, just look at it/[]/This regular expression, you will find that this rule can not match anything, because[]It means that any character in the character set needs to be matched, but the character set is empty, so any character does not match the character set, so/[]/Everything doesn’t match,[]yespattSo part of this rule does not match anything.

You can do it manuallypattChange into/{"name":"The child node of the first sentence, "content": "1children", "children": \[\]}/g,soon[]Use\If you remove the special meaning, you will find that the replacement is successful. The screenshots are as follows:

So you need to go firstJSON.stringify(obj2)Inside[]The code is as follows:

patt = new RegExp(JSON.stringify(obj2).replace(/\[|\]/g, "\\$&"), 'g');

The effect of the screenshot is as follows:

Answer 1:

Regular expressions do not match to..

Answer 2:

var patt = JSON.stringify(obj2);

Answer 3:

obj2The value converted to Json string is different from that in obj1, where obj1.children.children is converted to JSON string, console can be used.

Answer 4:
var newData = JSON.stringify(obj1).replace(patt,'1111111111111');

Change into

var newData = JSON.stringify(obj1).replace(JSON.stringify(obj2),'1111111111111');

Answer 5:

RegExpWhen you need to escape

Similar Posts:

Link of this Article: Why str.replace () has no effect

Leave a Reply

Your email address will not be published. Required fields are marked *