简体   繁体   中英

RegEx to find pattern “ JUNKCHARS” in Javascript string

Consider below String,

var originalStr = "This is first string JUNKCHARS";

I need a regex to find a pattern " JUNKCHAR", ie 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.

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

You can try something like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM