我试图从一个更大的字符串中提取一个字符串,它得到 a:
和 a 之间的所有内容;
当前的
Str = 'MyLongString:StringIWant;'
期望输出
newStr = 'StringIWant'
我试图从一个更大的字符串中提取一个字符串,它得到 a:
和 a 之间的所有内容;
当前的
Str = 'MyLongString:StringIWant;'
期望输出
newStr = 'StringIWant'
你可以试试这个
var mySubString = str.substring(
str.indexOf(":") + 1,
str.lastIndexOf(";")
);
你也可以试试这个:
var str = 'one:two;three';
str.split(':').pop().split(';')[0]; // returns 'two'
利用 split()
var s = 'MyLongString:StringIWant;';
var arrStr = s.split(/[:;]/);
alert(arrStr);
arrStr
将包含由:
or分隔的所有字符串;
所以通过访问每个字符串for-loop
for(var i=0; i<arrStr.length; i++)
alert(arrStr[i]);
@Babasaheb Gosavi 如果您有一次出现子字符串(“:”和“;”),则答案是完美的。但是一旦出现多次,它可能会变得有点棘手。
我想出的处理多个项目的最佳解决方案是在一个对象中使用四种方法。
说了这么多,让我们看看代码:
var getFromBetween = {
results:[],
string:"",
getFromBetween:function (sub1,sub2) {
if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return false;
var SP = this.string.indexOf(sub1)+sub1.length;
var string1 = this.string.substr(0,SP);
var string2 = this.string.substr(SP);
var TP = string1.length + string2.indexOf(sub2);
return this.string.substring(SP,TP);
},
removeFromBetween:function (sub1,sub2) {
if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return false;
var removal = sub1+this.getFromBetween(sub1,sub2)+sub2;
this.string = this.string.replace(removal,"");
},
getAllResults:function (sub1,sub2) {
// first check to see if we do have both substrings
if(this.string.indexOf(sub1) < 0 || this.string.indexOf(sub2) < 0) return;
// find one result
var result = this.getFromBetween(sub1,sub2);
// push it to the results array
this.results.push(result);
// remove the most recently found one from the string
this.removeFromBetween(sub1,sub2);
// if there's more substrings
if(this.string.indexOf(sub1) > -1 && this.string.indexOf(sub2) > -1) {
this.getAllResults(sub1,sub2);
}
else return;
},
get:function (string,sub1,sub2) {
this.results = [];
this.string = string;
this.getAllResults(sub1,sub2);
return this.results;
}
};
var str = 'this is the haystack {{{0}}} {{{1}}} {{{2}}} {{{3}}} {{{4}}} some text {{{5}}} end of haystack';
var result = getFromBetween.get(str,"{{{","}}}");
console.log(result);
// returns: [0,1,2,3,4,5]
var s = 'MyLongString:StringIWant;';
/:([^;]+);/.exec(s)[1]; // StringIWant