用单引号括起来并用正则表达式替换换行符

时间:2013-12-20 03:10:44

标签: javascript regex

我有以下字符串

Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School
Autism Partnership School

我想通过正则表达式更改它,如下所示:

'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 'Autism Partnership School', 

我已尝试replace(/^(.*)$/, '$&',)然后replace(/\r\n/, '')并且它有效。但是我不想两次替换,所以我将这种语法结合到replace(/^(.*)$\r\n/, '$&',)。有人可以告诉我为什么我的语法不起作用吗?

谢谢。

现场演示 http://regexr.com?37nk7

2 个答案:

答案 0 :(得分:2)

对于正则表达式,您应该能够使用它:

replace(/^(.*)$[\r\n]*/g, "'$1', ")

[\r\n]*只是为了考虑不同的EOL情景,以防万一。然后$1作为单个组的反向引用,regexp对象末尾的尾随g是用于全局执行替换的“全局”标志。

更新了演示:http://regexr.com?37nkd

答案 1 :(得分:-1)

implode("', '", explode("\n", $longString))

编辑#1: 哎呀,忘了JS而不是PHP。

var longStringArray = longString.split("\n");
var newLongString = longStringArray.join("', '");