[英]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
讓我們逐一介紹一下這種模式
\\s+
JUNKCHARS
$
在一起,您將獲得var pattern = /\\s+JUNKCHARS$/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.