删除多余的;#字符串中的实例

Remove extra ;# instances from string

本文关键字:实例 字符串 多余 删除      更新时间:2023-09-26

这是一个JavaScript问题。

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

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

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

放弃约翰·史密斯:

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

丢弃无名氏:

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

丢弃夏洛特勃朗特:

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

你能提供一个正则表达式吗?我可以用它来消除剩余的冒犯;#?


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

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

以下表达式可用于解析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"/>

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,""));
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>

这只是匹配其中之一:

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

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

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
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>