简体   繁体   English

RegEx在Javascript字符串中找到模式“ JUNKCHARS”

[英]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. 我需要一个正则表达式来找到模式“ JUNKCHAR”,即,字符JUNKCHAR之前(任意数量的)空白,之后是字符串的结尾。

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 这是一个演示: http : //jqversion.com/#!/NYBiNrT

You can try something like this: 您可以尝试如下操作:

(?:^|\\s)(JUNKCHARS)(?=\\s|$)|\\sJUNKCHARS\\s (?:^ | \\ 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+ 您想匹配多个空格,但至少要匹配一个,这样我们就可以\\s+
  2. You want to match the string JUNKCHARS 您要匹配字符串JUNKCHARS
  3. You want the end of the string, which is $ in regex syntax 您需要字符串的结尾,即正则表达式语法中的$

Together you'll get var pattern = /\\s+JUNKCHARS$/ 在一起,您将获得var pattern = /\\s+JUNKCHARS$/

You can fiddle around with it http://regex101.com/r/sU4eI3/1 您可以使用它http://regex101.com/r/sU4eI3/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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