我有一个字符串和一个数组:
var first = 'b c da e f a s';
var second = ["g","h","i","j","a"];
我需要在字符串中找到第一次出现的" a",从数组派生为最后一个字符,所以我做了:
var first = 'b c da e f a s';
var second = ["g","h","i","j","a"];
var myArray = second.reverse();
var arrayLength = myArray.length;
for (var i = 0; i < arrayLength; i++) {
var x = first.split(myArray[i])[1];
if (typeof x !== 'undefined'){
alert($.trim(myArray[i] + x))
break;
}
}
这会输出a e f
,而它应该是a s
。显然它会将单词da
拆分,但我只需要将它拆分为整个值,因此它应该跳过da
,除非我在寻找整个值da
答案 0 :(得分:1)
输出为a
,s
为newArray
的值。如果您需要字符串,可以内爆newArray
。
按空格分割字符串。循环遍历数组,如果针在大海捞针中,则从该位置切割数组。
var needle = 'a';
var haystack = 'b c da e f a s';
var parts = haystack.split(" ");
for (i=0; i < parts.length; i++) {
if (parts[i] === needle) {
var newArray = parts.slice(i);
break;
}
}
console.log(newArray);
答案 1 :(得分:1)
这是一种奇怪的方式,但是如果你真的需要这个,可以在second
中的每个字符串的全字版本上拆分字符串:
var first = 'b c da e f a s';
var second = ["g", "h", "i", "j", "a"];
var myArray = second.reverse();
var arrayLength = myArray.length;
for (var i = 0; i < arrayLength; i++) {
var x = first.split(new RegExp('\\b' + myArray[i] + '\\b'))[1];
if (typeof x !== 'undefined') {
alert($.trim(myArray[i] + x))
break;
}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;
答案 2 :(得分:1)
您的代码按照书面形式运作:
myArray (after reverse) -> ['a', 'j', 'i', 'h', 'g']
0 1 2 3 4
i = 0 -> myArray[i] -> 'a'
first.split('a')[1] -> ['b c d', ' e f ', 's'][1] -> ' e f ';
0 1 2
alert('a' + ' e f ') -> 'a e f';
然后你打破;并终止循环。
答案 3 :(得分:1)
function find_remainders(first, second) {
var words = first.split(' '); // Split up first by spaces
var result = '';
for (var i = second.length - 1; i >= 0; i--) { // Loop from the end of second until we succeed
var search = second[i]; // Get the current element of second
var index = words.indexOf(search); // Find that element
if (index != -1) { // If it was found
result = words.slice(index).join(' '); // Get it and everything after it, put back into a string
break;
}
}
return result;
}
alert(find_remainders('b c da e f a s', ["g", "h", "i", "j", "a"])); // a s
alert(find_remainders('b c da e f q s', ["g", "h", "f", "j", "a"])); // f q s
&#13;
答案 4 :(得分:1)
var first = 'b c da e f a s';
var second = ["g","h","i","j","a"];
var searchStr = second[second.length - 1];
var firstArray = first.split(' ');
for ( var i = 0; i < firstArray.length; i++) {
if ( firstArray[i] === searchStr) {
break;
}
}
if (i < firstArray.length) {
alert(firstArray.splice(i).join(' '));
}