I have the following sentence:
One Flew Over the Cuckoo's Nest
I'd like to remove any instance of "the" and "'" from the sentence so the output is the following:
Expected output:
one flew over cuckoos nest
I use the following code:
var guess = "One Flew Over the Cuckoo's Nest";
guess = guess.toLowerCase().replace("'", "").replace("the", "");
Actual Output:
one flew over cuckoos nest
The problem is that there's a space appearing after "over" because I'm only removing "the" from that particular sentence and not the space afterwards.
I know I can fix this by using replace("the ", ""); but I would like a better way to achieve the result.
Would there be a regular expression I can use instead?
2 Answers 2
One problem you will face is that replace only replaces the first match. In order to replace all of them, you need to use a regex with the global modifier.
guess = guess.toLowerCase().replace(/the|'/g,'').replace(/ +/g,' ');
The second replace contains two spaces followed by a +. This will fix any "broken" spaces caused by the words being removed. Also, in the first one an alternation is used to get both the the words and apostrophes in one shot.
1 Comment
"the", but it won't work with something like: "The King's Speech" => "kings speech".personally I would do
var guess = "One Flew Over the Cuckoo's Nest";
guess = guess.toLowerCase().replace("'", "").replace(" the", "").replace("the ", "");
I'm sure there's some regEx for this, but seems overkill
I'm not a regEx expert, so I can't offer you a solution in regEx
3 Comments
" the" so you could just go with replacing "the "