-1

Quick question.

Lets say I have:

var specialthings = ['special1','special2','special3'];
var alotoftext = ['randomTextButHereIHavespecial1orspecial2orspecial3']

My goal is to seperate specialthings from alotoftext. So the outcome would be new var or alot of text (same to me) to be equal to:

var newvar or var alotoftext = ['randomTextButHereIHaveor']

basically to remove special1 special2 and special3.

I don't want a remover like 0-9 if the case was numbers, but rather a function that would separate values of one string from another -- literally like this:

var new = alotoftext - specialthings

kind of an approach.

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
joe123
  • 47
  • 1
  • 7

2 Answers2

2

You can form a new regex seperating all the words with a pipe which you want to remove and then use .map on the array to replace all the occurences.

var specialthings = ['special1','special2','special3'];
var alotoftext = ['randomTextButHereIHavespecial1orspecial2orspecial3']

var re = new RegExp(specialthings.join("|"),"g");

var newText =  alotoftext.map(el => el.replace(re, ""));

console.log(newText);
void
  • 36,090
  • 8
  • 62
  • 107
  • Thank you, works like a charm! – joe123 Feb 27 '18 at 11:03
  • just a quick question tho... I see it doesn#t work if i have special chars, example if i have emojis.. any ideas of a workaround? – joe123 Feb 27 '18 at 11:09
  • @joe123 use escape characters in that case "\" – void Feb 27 '18 at 11:13
  • can you implement it in your solution :) – joe123 Feb 27 '18 at 11:16
  • @joe123 this is not appreciated here in SO. You can post another question describing your problem. Your question is meant to help other people as well but doing it this way makes the thread more confusing. I would ask you to close this thread by marking the answer correct and start a new thread. – void Feb 27 '18 at 11:21
  • Gotcha, thanks anways, il try to figure it out on my own. – joe123 Feb 27 '18 at 11:43
0

Use map and RegExp

var output = alotoftext.map( s => s.replace( new RegExp( specialthings.join( "|" ), "g" ), "" ) )

Demo

var specialthings = ['special1','special2','special3'];
var alotoftext = ['randomTextButHereIHavespecial1orspecial2orspecial3'];
var output = alotoftext.map( s => s.replace( new RegExp( specialthings.join( "|" ), "g" ), "" ) );
console.log( output );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94