Zhe*_*hen 29 javascript string cut
我有如下所示的字符串:
XXX:Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur cursus lacus sed
justo faucibus id pellentesque nunc porttitor. Sed venenatis tempor dui, nec mattis dolor
ultrices at. Duis suscipit, dolor sed fringilla interdum, magna libero tempor quam, sed
molestie dui urna sed tellus.
Run Code Online (Sandbox Code Playgroud)
如何在第一行添加限制并剪掉字符串?(使用javascript).
我期望的最终结果如下:
XXX:Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur...
Run Code Online (Sandbox Code Playgroud)
Tom*_*lak 67
var firstLine = theString.split('\n')[0];
Run Code Online (Sandbox Code Playgroud)
Wil*_*ilt 36
Tomalak他的答案是正确的,但是如果你真的只想匹配第一行,那么传递可选的第二个limit
参数会很有用.像这样你可以防止在返回第一个匹配之前将一个长字符串(有数千行)分割到结尾.
通过设置可选项limit
,1
我们告诉方法一旦找到第一个匹配就返回结果,结果是性能提高.
var firstLine = theString.split('\n', 1)[0];
Run Code Online (Sandbox Code Playgroud)
阅读有关限制参数的更多信息,例如MDN文档中的示例
Ale*_*pin 11
如果有实际的行返回,而不仅仅是某种自动换行,你可以这样做:
str = str.substr(0, str.indexOf("\n"));
Run Code Online (Sandbox Code Playgroud)
function getFirstLine(str){
var breakIndex = str.indexOf("\n");
// consider that there can be line without a break
if (breakIndex === -1){
return str;
}
return str.substr(0, breakIndex);
}
getFirstLine('first line\nsecond line'); // first line
getFirstLine('text without line break'); // text without line break
Run Code Online (Sandbox Code Playgroud)