Good day! Please tell me how a regular JS expression should look in order to remove a word from the comma?

For example, there is a line:

11, 22, 33, 44, 55 

If you decide to delete 11, it turned out

 22, 33, 44, 55 

If 55, then:

 11, 22, 33, 44 

That the comma was not lost and there were no superfluous commas. Thank!

  • Can words be comma-free or not? aaa, I would bvvd, ddd, at lll - Sergiks
  • @sergiks you wrote "and I vdul"? - Specter
  • @Spectre: the joke did not pass. Always hash with leprosy confusing. - Sergiks

3 answers 3

So it will be faster and safer than regexp:

 function rem_word(text, word) { return text.split(', ') //делим - ', ' .filter(function (e) { return e != word; //удаляем ненужные слова }).join(', '); //клеим } console.log(rem_word('11, 22, 33, 44, 55',11));

If you need regexp, like this:

 function rem_word2(text,word) { var reg=new RegExp(word+',\\s+|,\\s+'+word,'g'); return text.replace(reg,''); } 

In this case, the true cant can be with a string of type '55, 44, 33, 111 'and an attempt to delete 11 or 4, in general it’s better to split , if the space can not be one, then take an example from the comments.

  • ... if the number of spaces is constant. - VladD pm
  • This is a question about the quality of the data, and even so it can be done, if necessary, or so - zb '11
  • Very grateful, the number should be constant, I’ve hired it before with the help of indexOf, now I tend more to the rem_word function. Thanks again! - stasQa

For example :

 var s = "11, 22, 33, 44, 55, lalala, fafafa"; var parts = s.split(/,\s*/g); var indexToRemove = 0; parts.splice(indexToRemove, 1); s = parts.join(", "); 

(they say it might not work in IE, test it)

  • Why split with spaces? just split by comma, you delete by index. var parts = s.split (','); parts.splice (index, 1); s = parts.join (','); - Yura Ivanov
  • one
    @Yura Ivanov: for aesthetics, there is exactly one space everywhere after passing a function. - VladD
  • Well, for aesthetics, spaces are not needed at all. you just remove an arbitrary number of spaces, and insert only one, i.e. do not just delete, but also change the rest of the line. if they need these spaces, then maybe they are needed all ... - Yura Ivanov
  • @Yura Ivanov: if we have real comma-separated values, significant spaces should be enclosed in quotes (then the parser will be more difficult). In any case, what exactly is better suited to the problem let the vehicle decide. - VladD
  • I agree, the vehicle decides itself. I didn’t find fault with it, I just noticed that such a conversion is superfluous in terms of changing the input data unnecessarily ... - Yura Ivanov

For example:

 function numReplace(text, num) { return text.replace(new RegExp("\\b"+num+"\\s*,\\s*(?=\\S)|\\b,\\s*"+num+"\\s*$|^\\s*"+num+"\\s*$", "g"), ""); }; 

That's all, the final version (I’m correcting the tenth comment already).