删除多余的;#字符串中的实例
Remove extra ;# instances from string
这是一个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>
相关文章:
- 删除数组Javascript中字符串的所有实例
- 如何通过JS在不干扰其标记的情况下更改HTML文档中字符串的所有实例
- 是否有将基于字符串的JSON转换为Mongoose Schema对象实例的本地功能
- JavaScript:计算字符串中特定整数的实例
- 从 Node.js 模块中的缓冲区实例中逐行读取字符串
- 正则表达式来更改字符串中的所有实例
- javascript正则表达式,将多个实例替换为多行字符串中的单个实例
- 如何更改字符串/符号的所有实例的样式
- 替换字符串中YouTube/Vimeo iframe的所有实例
- 字符串是对象 String() 的实例吗?
- 我们如何在 javascript 对象中使用字符串名称存储创建 Backbone 视图的实例
- 如何匹配并返回一个字符串的多个实例,其中单个撇号可以包含在任何索引中
- Jquery:在一个字符串中查找所有实例模式,提示用户替换模式的所有实例,然后进行替换
- Ember.js:使用模型实例的路由获取模型实例的 url 字符串
- 如何在 JavaScript 中替换字符串中“+”的多个实例
- 查找字符串中单词所有实例的位置,在控制台中得到不需要的重复
- 正则表达式 Express 将反斜杠 的每个实例替换为字符串中的 u
- 按第三个实例拆分字符串
- 使用其他javascript删除字符串中某个字符的所有实例
- 删除多余的;#字符串中的实例