Skip to content Skip to sidebar Skip to footer

How To Remove A Part Of The String Using Arrays

I want to remove(technically replacing) the words int, float, char, bool, main, void main, int main, cout, cin to '' (like removing it) if it is found on the string. So if i have t

Solution 1:

for(int i=0; i<kWord.length; i++) {
  str = str.replace(kWord[i],"");
}

of course this will also convert mainframe to frame, integer to eger, etc. It also won't hit all occurences, just the first. If you need to avoid substrings like that you might need to put some more thought into it, and use a regex that checks for word boundaries

/\bfoo\b/g

Solution 2:

You can do the same as in the answer to your other question, but building a regex object using kWord.join('|').

kWord[0] = 'int';
kWord[1] = 'float';
kWord[2] = 'char';
kWord[3] = 'bool';
kWord[4] = 'main';
kWord[5] = 'void\\s+main';
kWord[6] = 'int\\s+main';
kWord[7] = 'cout';
kWord[8] = 'cin';

var r = '\\b(' + kWord.join('|') + ')\\b';
var myRegex = new RegExp(r, 'g');
str = str.replace(myRegex, "");

Post a Comment for "How To Remove A Part Of The String Using Arrays"