在javascript中,我有一个像
这样的大字符串str="a lot of lines\n"
str+="foo\n"
str+="the stuff I want\n"
str+="bar and a lot more stuff\n"
我如何只放置零件:
the stuff I want
“foo”和“bar”之间的新字符串变量?
答案 0 :(得分:4)
根据字符串中“你想要的东西”的确切位置,你可以采用与此相似的方法:
var str="a lot of lines\n";
str+="foo\n";
str+="the stuff I want\n";
str+="bar and a lot more stuff\n";
var stuff = str.split('\n')[2]; // the stuff i want
编辑: 如果你想要foo和bar之间的东西,那么你可以做类似的事情:
var stuff = str.match(/foo((.|\n)*)bar/)[1]; // contains newlines!
答案 1 :(得分:3)
var str = "a lot of lines foo the stuff I want bar and a lot more stuff"
str.substring(str.indexOf("foo")+3,str.indexOf("bar") )
答案 2 :(得分:-1)
var str="a lot of lines\n";
str+="foo\n";
str+="the stuff I want\n";
str+="bar and a lot more stuff\n";
// ------------------------------
var myRegex = /foo(.*)bar/;
if (myRegex.test(str)) {
alert(myRegex[0]);
}
使用正则表达式,它应该可以解决问题。