0

Consider below String,

var originalStr = "This is first string JUNKCHARS";

I need a regex to find a pattern " JUNKCHAR", i.e. characters JUNKCHAR with (any number of) whitespace before it and end of string after it.

e.g, 

// case 1
originalStr = "This is first string JUNKCHARS";

replacedStr = originalStr.replace(<pattern>, "");

console.log(replacedStr); // should output - This is first string

// case 2
originalStr = "This is first string            JUNKCHARS";

replacedStr = originalStr.replace(<pattern>, "");

console.log(replacedStr); // should output - This is first string

// case 3
originalStr = "This is first string JUNKCHARS    ";

replacedStr = originalStr.replace(<pattern>, "");

console.log(replacedStr); // should output - This is first string JUNKCHARS    

// case 4
originalStr = "This is first string JUNKCHARS test";

replacedStr = originalStr.replace(<pattern>, "");

console.log(replacedStr); // should output - This is first string JUNKCHARS test    

// case 5
originalStr = "This is first stringJUNKCHAR";

replacedStr = originalStr.replace(<pattern>, "");

console.log(replacedStr); // should output - This is first stringJUNKCHAR

// case 6
originalStr = "This is first string JUNKCHARtest";

replacedStr = originalStr.replace(<pattern>, "");

console.log(replacedStr); // should output - This is first string JUNKCHARtest

I have tried several regex but none seems to meet my requirement. Could anyone please help me in finding the right regex. Your help will be appreciated.

2
  • So in case 3 for instance, we do NOT remove JUNKCHAR? Not understanding the rule.
    – zx81
    Jul 17, 2014 at 6:51
  • yes, we do not remove JUNKCHAR because there is a space after it.
    – Muthu
    Jul 17, 2014 at 7:08

3 Answers 3

0

Let's go through that pattern by part

  1. You want to match a number of whitespaces, but at least one, so that gives us \s+
  2. You want to match the string JUNKCHARS
  3. You want the end of the string, which is $ in regex syntax

Together you'll get var pattern = /\s+JUNKCHARS$/

You can fiddle around with it http://regex101.com/r/sU4eI3/1

0
0

You may try something like this:

var text = 'This is first string JUNKCHARS    ';
text = text.replace(/\s{2,}JUNKCHARS/g,'').trim();
console.log(text);

Here is a demo: http://jqversion.com/#!/NYBiNrT

0

You can try something like this:

(?:^|\s)(JUNKCHARS)(?=\s|$)|\sJUNKCHARS\s

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.