This question has already been answered:

The task is to divide arbitrary text and remove unnecessary possible characters, such as "." or for example ",". How to do it? It worked for me in the console, but in the whole code does not work. And how to check for all possible signs? For each write a separate line? After all, it can also be "!" be for example.

var text = prompt('Введите любой произвольный текст', 'Футбол это игра, целью которой является забить мяч в ворота противника'); var textArr = text.split(' '); for (i = 0; i < textArr.length; i++) { textArr[i].replace(',', ''); }; 

Reported as a duplicate at Grundy. javascript 6 Sep '17 at 10:47 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • @Grundy, well, what a duplicate, if, judging by the question, he generally needs such an answer: var textArr = text.split(/[\s,]+/).filter(Boolean); and without any cycles and replacements. - Qwertiy
  • @Qwertiy, there is about replace, and here about replace - everything is ok :-) Well, in this case it’s more like .match(/[а-я]+/gi) and not on split :) - Grundy
  • @Grundy, what about az ?) And match still has a null case that gets mixed up) - Qwertiy
  • @Qwertiy, for example, it was :-) - Grundy

2 answers 2

Because you need to read the description of the function String.prototype.replace () - this method does not change the calling string, but returns a new one after the replacements.

For the replacement, use the assignment.

 var text = prompt('Введите любой произвольный текст', 'Футбол это игра, целью которой является забить мяч в ворота противника'); var textArr = text.split(' '); for (i = 0; i < textArr.length; i++) { textArr[i] = textArr[i].replace(',', ''); }; 
  • and how then to replace? - PolonskiyP
  • one
    @PolonskiyP supplemented the answer, it is necessary to replace the old value in the array with the new one, which returns replace. - Alex Krass
  • Thanks, works!) - PolonskiyP
  • .replace(',', '') - replaces only the first comma. - Qwertiy
  • @PolonskiyP, then accept the answer by clicking on the check mark to the left of it. But in general, I suspect that instead of all this you need var textArr = text.split(/[\s,]+/).filter(Boolean); - Qwertiy
 var text = prompt('Введите любой произвольный текст', 'Футбол это игра, целью которой является забить мяч в ворота противника'); var textArr = text.replace(',', '').split(' '); 

UPD:

 var text = prompt('Введите любой произвольный текст', 'Футбол это игра, целью которой является забить мяч в ворота противника'); var textArr = text.replace(/[,!]/g, '').split(' '); 
  • .replace(',', '') - replaces only the first comma. - Qwertiy
  • Well .replace('/[,!]/g', '') ... - Akina
  • Not '/[,!]/g' , but simply /[,!]/g - Qwertiy