【问题标题】:Remove special character from the starting of a string and search @ symbol.in javascript从字符串的开头删除特殊字符并搜索@symbol.in javascript
【发布时间】:2013-01-15 05:48:43
【问题描述】:

我只想从字符串的开头删除特殊字符。 即,如果我的字符串类似于{abc@xyz.com,那么我想从一开始就删除{。字符串应该看起来像 abc@xyz.com

但如果我的字符串类似于abc{@xyz.com,那么我想保留与它相同的字符串,即abc{@xyz.com

我还想检查我的字符串是否存在@符号。如果存在,则 OK,否则显示一条消息。

【问题讨论】:

标签: javascript


【解决方案1】:

以下演示了您指定的内容(或已接近):

var pat = /^[^a-z0-9]*([a-z0-9].*?@.*?$)/i; //pattern for optional non-alphabetic start followed by alphabetic, followed by '@' somewhere
var testString = "{abc@xyz.com"; //Try with {abcxyz.com for alert
arr = pat.exec(testString);
var adjustedString;
if (arr != null) { adjustedString = arr[1]; }  //The potentially adjustedString (chopped off non-alphabetic start) will be in capture group 1
else { adjustedString = "";  alert(testString + " does not conform to pattern"); }
adjustedString;

【讨论】:

  • :- 非常感谢..但是如果我在开头得到多个括号或任何其他特殊字符,例如 {#!abc@xyz.com。我只想从开头消除特殊字符(即,直到收到第一个字符或整数)??任何帮助将不胜感激!
  • 嗨,我根据您的 cmets 编辑了答案。现在,多个非字母、非数字字符将在开头被剥离。我这样做的方法是使用 *,如果没有,则匹配 0 个这样的字符,或者一个或多个。
【解决方案2】:

我使用了两个单独的正则表达式对象来实现您的要求。它检查字符串中的两个条件。我知道它不是很有效,但它会满足您的目的。

var regex = new RegExp(/(^{)/);
var regex1 = new RegExp(/(^[^@]*$)/);
var str = "abc@gmail.com";
if(!regex1.test(str)){
     if(regex.test(str))
         alert("Bracket found at the beginning")
      else
        alert("Bracket not found at the beginning")
}
else{
   alert("doesnt contain @");
}

希望对你有帮助

【讨论】:

  • 另外,如果您需要电子邮件验证,这里是一个很好的线程stackoverflow.com/questions/46155/…。但是,正如帖子建议的那样,电子邮件验证也应该在服务器端完成
猜你喜欢
  • 1970-01-01
  • 2023-01-07
  • 2011-11-13
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 2016-01-23
相关资源
最近更新 更多