繁体   English   中英

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

[英]RegEx to find pattern “ JUNKCHARS” in Javascript string

考虑下面的字符串,

var originalStr = "This is first string JUNKCHARS";

我需要一个正则表达式来找到模式“ 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

我已经尝试了几种正则表达式,但似乎都没有满足我的要求。 任何人都可以帮助我找到正确的正则表达式。 您的帮助将不胜感激。

您可以尝试如下操作:

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

这是一个演示: http : //jqversion.com/#!/NYBiNrT

您可以尝试如下操作:

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

让我们逐一介绍一下这种模式

  1. 您想匹配多个空格,但至少要匹配一个,这样我们就可以\\s+
  2. 您要匹配字符串JUNKCHARS
  3. 您需要字符串的结尾,即正则表达式语法中的$

在一起,您将获得var pattern = /\\s+JUNKCHARS$/

您可以使用它http://regex101.com/r/sU4eI3/1

暂无
暂无

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

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