簡體   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