My current challenge involves removing only sequential duplicates from a string. For example, in the string "1 2 3 3 2 1", I want to remove one of the consecutive 3's so it becomes "1 2 3 2 1". I thought I had the solution figured out, but when I tested it, I encountered a scenario where it failed. Despite trying various combinations, nothing seems to work. It must be something simple that I am missing.
Below is some Javascript code demonstrating the issue. The first testVal string is handled correctly, but the commented-out testVal string does not produce the correct result.
// The following string should reduce to: MTC MTCA MTC ORD MTC (it does).
var testVal = "MTC MTC MTCA MTC MTC MTC ORD MTC";
// The following string should reduce to: MTC (it does not. Result = MTC MTC).
// The string MTC MTC MTC MTC also only reduces to MTC MTC, so I'm thinking
// it's a whitespace issue.
// var testVal = "MTC MTC";
while (/\b(\s*\w+\s*)\b\1/.test(testVal)) {
testVal = testVal.replace(/\b(\s*\w+\s*)\b\1/g,'$1');
}
alert(testVal1);