簡體   English   中英

如何使用正則表達式-Javascript檢查字符串中是否存在“未定義”測試

[英]How to check for an “undefined” test present in the string using regex-Javascript

我在正則表達式后的末尾得到了未定義的附加到字符串的信息,例如:

var string="test.testA:(number:'1')undefined' 

有時它會附加為字符串

var string2 = "test.testA:(number:'1') and undefined"

基本上這可以在任何地方,我想使用正則表達式刪除它。 正則表達式是否檢查字符串中是否存在未定義的內容? 如果不是,那么最好的解決方案是刪除字符串中存在的“未定義”測試?

謝謝!

對於您的兩個示例字符串,這將刪除字符串中關閉括號后的所有內容。

var foo = inputString.replace(/[\w\s]*undefined\s*$/i, '');
  • \\ w-az,AZ,0-9,_中的任何一個
  • \\ s-空格和制表符
  • [] *-內部包含0或更多的任何模式
  • undefined-文字“ undefined”
  • \\ s *-0個或更多空格/制表符
  • $-字符串結尾
  • i-//里面的所有內容都不區分大小寫(在這種情況下,單詞“ undefined”

如果您要刪除輸入中包含未定義單詞的所有內容,那么@Toto的答案就是解決方法。

 // remove only "undefined" var test = [ "test.testA:(number:'1')undefined", "test.testA:(number:'1') and undefined", ]; console.log(test.map(function (a) { return a.replace(/\\bundefined\\b/, ''); })); // remove the whole line var test2 = [ "test.testA:(number:'1')undefined", "test.testA:(number:'1') and undefined", ]; console.log(test2.map(function (a) { return a.replace(/^.*?\\bundefined\\b.*$/, ''); })); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM