简体   繁体   中英

JavaScript Surround quotes around a single string in multi lines

My string is somewhat like this :

<rules>
  <transTypeRuleList>
    <transType type='stocks'>
      <criteria result='401kContribution' priority='0'>
        <field compare='contains' name='description'></field>
      </criteria>
      <criteria result='401kContribution' priority='1'>
        <field compare='contains' name='description'></field>
      </criteria>
    </transType>
  </transTypeRuleList>
</rules>

I need to take this and paste it in eclipse as a string , I know eclipse has an option to escape multi line strings and all, but that gives me the string as with "\\n \\r" Which I don't want .

My ideal string would be just the Double quotes and a + at the end of each line somewhat like this.

var res= "<rules>"+
    "<acctTypeRuleList>"+
    "<acctTypetype='stocks'>"+
    "<criteriaresult='individual'priority='0'>"+
    "<fieldcompare='contains'name='accountName'></field>"+
    "</criteria>"+
    "<criteriaresult='individual'priority='1'>"+
    "<fieldcompare='contains'name='accountName'></field>"+
    "</criteria>"+
    "</acctType>"+
    "</acctTypeRuleList>"+
    "<transTypeRuleList>"+
    "<transTypetype='stocks'>"+
    "<criteriaresult='401kContribution'priority='0'>"+
    "<fieldcompare='contains'name='description'></field>"+
    "</criteria>"+
    "<criteriaresult='401kContribution'priority='1'>"+
    "<fieldcompare='contains'name='description'></field>"+
    "</criteria>"+
    "</transType>"+
    "</transTypeRuleList>"+
    "</rules>";

While preserving the indentation. So I am looking at regex.

So I guess finding ^(.*)$ and replacing with "$1" + should have done the job but it doesn't work .

Have a look at the fiddle. :

Link

Thanks in advance.

This seems to work:

http://regexr.com/38ps2

What I did

  • added the multiline m switch
  • removed the empty line in the text. Looks like regexr has problems with that.

I'd try with this:

'var res = "' + xml.replace(/\r?\n\s*/g, '" +\r\n\t"') + '";';

But remember that Javascript does allow multiline strings. Just put a backslash at the end of each line:

"<rules>\
  <transTypeRuleList>\
...\
</rules>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM