简体   繁体   English

JavaScript Surround用引号将多行中的单个字符串引起来

[英]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 . 我需要将其作为字符串粘贴到eclipse中,我知道eclipse可以选择转义多行字符串和所有字符串,但这给了我不需要的字符串,例如"\\n \\r"

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 . 所以我想找到^(.*)$并替换为"$1" +应该可以完成这项工作,但是不起作用。

Have a look at the fiddle. 看看小提琴。 :

Link 链接

Thanks in advance. 提前致谢。

This seems to work: 这似乎可行:

http://regexr.com/38ps2 http://regexr.com/38ps2

What I did 我做了什么

  • added the multiline m switch 添加了多行m开关
  • removed the empty line in the text. 删除了文本中的空行。 Looks like regexr has problems with that. 看起来regexr有问题。

I'd try with this: 我会尝试这样做:

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

But remember that Javascript does allow multiline strings. 但是请记住,JavaScript 确实允许多行字符串。 Just put a backslash at the end of each line: 只需在每行末尾加一个反斜杠:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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