获得有条件的角色位置

时间:2016-01-14 15:29:42

标签: javascript

我得到了一些包含别名的字符串(例如" MM")。 我使用' @'来启动别名。字符。 String可能看起来像#34;此消息转到@ GR,MM。很高兴见到你!"。也许也" @GR这种情绪不是很有效,但也应该有效,MM"

我的函数必须从字符串中删除给定的别名。也许最好也是唯一的方法是在别名旁边检查左右(" @"或",")。 有人想知道如何在别名旁边左右检查以决定是否删除?

underscore.js和underscore.string是o.k

示例:

function removeAlias(别名,描述)返回描述

如果说明包含别名,请删除并在没有它的情况下返回

例:

" @ME,MH在此字符串中,删除MH" 结果:@ME在此字符串中,删除MH"

" @MH在此字符串中,删除MH" 结果:在此字符串中,删除MH

" @GR在此字符串中,删除,MH" 结果:" @GR在此字符串中,删除"

2 个答案:

答案 0 :(得分:0)

根据您发布的案例,我认为这可能是您想要的

function removeAlias(alias, description) {
    return description.replace(new RegExp('[@,]*' + alias + ' *'), '');
}

答案 1 :(得分:-1)

查找Regular Expressions并使用String.replace:

function removeAlias(alias, text) {

  // look for a 'word boundary' (\b)
  // followed by zero or more '@' caracters (@*)
  // followed by the given alias
  // followed by another 'word boundary'
  var regex = new RegExp("\b@*"+alias+"\b");
  // replace by empty string
  var result = text.replace(regex, "");
  return result;
}

也许您需要根据实际需求调整实际正则表达式。