0

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?

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This seems to do the trick for the removal of "the", but it won't work with something like: "The King's Speech" => "kings speech".
2

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

Yeah, I'm not a big regex expert myself. I think I'll just use the two replaces in the end.
Are these all titles? It may be safe to assume none of the strings end in " the" so you could just go with replacing "the "
Yeah, they're all titles. I could probably just get away with your answer actually. I'll run some tests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.