Эй, ребята, я работаю над проблемой, которая ищет строку и заменяет x на y в моем случае до & после. Но почему-то мой метод splice() просто возвращает удаленный элемент. и thats, где im фактически застрял на ..... Взгляните на мой код ниже, спасибоJavascript splice method confusion
function replace(str, before, after) {
/* logic
1. put the string into an array with split()
2. search array index and replace 2nd argument with 3rd argument
3. turn array back into string wtih join() method
*/
// turn string into an array
var strIntoArray = str.split(' ');
// looping thru array
for(i = 0; i < strIntoArray.length; i++){
//compare index to arguments
if (strIntoArray[i] === before) {
// replace index with arguments with splice() method
// this part is a lot more complex
console.log(strIntoArray.splice(strIntoArray.indexOf(before), 1, after));
}
}
//console.log(strIntoArray);
}
replace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
Если вам нужна часть массива в новой переменной, используйте срез вместо сращивания –