从字符串中删除额外的; #instore

时间:2014-10-10 14:25:53

标签: javascript regex

这是一个JavaScript问题。

我有一个字符串(SharePoint帐户名列表),可以在字符串中的任何位置删除用户帐户。例如:

"1;#Smith, John;#47;#Doe, Jane;#13;#Bronte, Charlotte"

我的代码设置为根据用户选择删除其中一个帐户字符串,但在字符串的开头,中间或末尾留下了一个;#分隔符。

放弃约翰史密斯:

";#47;#Doe, Jane;#13;#Bronte, Charlotte"

放弃Jane Doe:

"1;#Smith, John;#;#13;#Bronte, Charlotte"

放弃Charlotte Bronte:

"1;#Smith, John;#47;#Doe, Jane;#13;#"

你能提供一个我可以用来杀死剩余犯罪的正则表达式吗?#?


以下是删除代码,其中existingUsers是完整字符串,account是从字符串中删除的名称:

if (existingUsers.length > account.length) {
  existingUsers.replace(account, "");
  // Clean up leftover ;# - regex
} else {
  existingUsers = "";
}

2 个答案:

答案 0 :(得分:1)

以下表达式可用于解析SharePoint用户字段值:

((\d+));[#]([(\w*\\)+\s]+)

如何解析JavaScript中的用户字段值



function parseMultiColumnValue(fieldValue)
{
    var re = /((\d+));[#]([(\w*\\)+\s]+)/g;
    var results = [],match;
    while (match = re.exec(fieldValue)) {
       results.push({'Id' : parseInt(match[1]), 'Value': match[3]});
    }
    return results;
}  



//Tests
   
//Parse values
var values = parseMultiColumnValue('1;#user1;#4;#user2;#10;#user3');
$('div#output').append(JSON.stringify(values));

//Delete the first item 
values.splice(0, 1);
$('div#output').append(JSON.stringify(values));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"/>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
var r = /(^;#|;#(?=;#)|;#$)/;
var s1 = ";#47;#Doe, Jane;#13;#Bronte, Charlotte";
var s2 = "1;#Smith, John;#;#13;#Bronte, Charlotte";
var s3 = "1;#Smith, John;#47;#Doe, Jane;#13;#";

console.log(s1.replace(r,""));
console.log(s2.replace(r,""));
console.log(s3.replace(r,""));
&#13;
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
&#13;
&#13;
&#13;

这简单地匹配:

^;#         start of string followed by ;#
;#(?=;#)    ;# followed by another ;#
;#$         ;# followed by end of string

正如其他人所建议的那样,将字符串拆分为数组可能更容易。如果你必须有一个字符串,你可以join再次将它重新组合在一起:

&#13;
&#13;
var s = "1;#Smith, John;#47;#Doe, Jane;#13;#Bronte, Charlotte";
var account = "1;#Smith, John";   // for example
var search = account.split(";#");
var split = s.split(";#");    
var i = split.indexOf(search[0]);  // search by number first
if (i!==-1 && split[i+1] === search[1]) {   // check the username matches too!
    split.splice(i,2);         // we remove the matching elements
    console.log(split);        // John Smith was removed
}
console.log(split.join(";#")); // If you must have a string after removing a user
&#13;
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
&#13;
&#13;
&#13;