How can javascript replace a word in the text without using replace ?

 var text = "Этот трактат по теории этики был очень популярен в эпоху Возрождения"; 

Here it is necessary to replace the word "theory" with "practice".

  • one
    Give an example of the text, and an example of the result for it. And it would also be good to indicate what you do not like. replace - Grundy
  • edit your question and paste this code snippet into it. There is a question to edit button. - Grundy
  • 2
    what is wrong with replace ? why do you need it without him? - Grundy
  • 9
    read, once trained about split() / join() - Alexander Igorevich
  • one
    If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

As a simple replacement for the replace method, you can use a couple of split and join methods.

In this form:

 str.split('подстрока которую заменить').join('строка на которую заменить'); 

Example:

 var text = "test 1, test 2, test 3, test 4, test 5, test 6"; document.body.innerHTML = text + '<br/>'+ text.split('test').join('newTest'); 

  • Thank! what you need) - Yaroslav
  • I would not have thought so)) - Jean-Claude
  • @Yaroslav if you were given the correct answer, check it with a daw. - Denis
  • @ Jean-Claude, how would you think of it? You can post the next answer - Grundy
  • By the way about the "simple" you got excited. This is a great implementation of replace_all which is not in JavaScript (if without regexps). I recommend to add what is still different str.replace('a', 'b'); from str.split('a').join('b'); - tutankhamun

For variety, you can also substitute with indexOf() and substring() . More precisely, it is no longer "replacement" but "copy / cut / paste" , but it also works.

 function replace(str, find, word) { var result = str, i = 0, len = find.length; while (len) { i = result.indexOf(find, i); if (i == -1) { break; } result = result.substring(0, i) + word + result.substring(i + len); i += len; } return result; } var newStr = replace("Этот трактат по теории этики", "по теории", "на практике"); console.log(newStr); // Этот трактат на практике этики 

  • it would be indexOf saving the indexOf result :-) indexOf way, if you change it to the same value, then the cycle will never end :) - Grundy
  • @Grundy yes) endless while we can get a bonus. Completed :) - Alexander Igorevich February
  • @AlexanderIgorevich Doubtful bonus :) I allowed myself to correct your answer a bit - tutankhamun
  • @tutankhamun, somehow not very corrected :-) len does not change the meaning of it while checking? - Grundy
  • @Grundy if find is empty, the loop will loop. It turns out: one rake removed, others put - tutankhamun