javascript - JS : Extracting specific text from a string

标签 javascript

我有一个像这样的字符串...

var str = "6 validation errors detected: Value '' at 'confirmationCode' failed to satisfy constraint: Member must satisfy regular expression pattern: [\S]+; Value '' at 'confirmationCode' failed to satisfy constraint: Member must have length greater than or equal to 1; Value at 'password' failed to satisfy constraint: Member must satisfy regular expression pattern: [\S]+; Value at 'password' failed to satisfy constraint: Member must have length greater than or equal to 6; Value at 'username' failed to satisfy constraint: Member must satisfy regular expression pattern: [\p{L}\p{M}\p{S}\p{N}\p{P}]+; Value at 'username' failed to satisfy constraint: Member must have length greater than or equal to 1";

我想提取所有以单词...“Value”...开头的“独特”行...

所以预期的输出是......

  • “confirmationCode”处的值“”未能满足约束
  • “password”的值未能满足约束
  • “用户名”的值未能 满足约束

这是我到目前为止所尝试过的......

var x = str.split("\;|\:")  // This is NOT working
console.log(x);

var z = y.filter(word => word.indexOf("Value") > -1) // Also this needs to be tweaked to filter unique values
console.log(z);

性能是一个问题,所以我更喜欢最优化的解决方案。

最佳答案

您可以使用单个正则表达式,不需要 splitfilter 或循环或其他测试:

var str = "6 validation errors detected: Value '' at 'confirmationCode' failed to satisfy constraint: Member must satisfy regular expression pattern: [\S]+; Value '' at 'confirmationCode' failed to satisfy constraint: Member must have length greater than or equal to 1; Value at 'password' failed to satisfy constraint: Member must satisfy regular expression pattern: [\S]+; Value at 'password' failed to satisfy constraint: Member must have length greater than or equal to 6; Value at 'username' failed to satisfy constraint: Member must satisfy regular expression pattern: [\p{L}\p{M}\p{S}\p{N}\p{P}]+; Value at 'username' failed to satisfy constraint: Member must have length greater than or equal to 1";

console.log(
  str.match(/((^|Value)[^:]+)(?!.*\1)/g)
);

关于javascript - JS : Extracting specific text from a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50904353/

相关文章:

javascript - 如何让 Discord Bot 跳过删除包含 *DD 的消息

javascript - 围绕索引重新排序数组

javascript - AngularJS 不显示模板

javascript - 在查找 3 个字符的字符串排列的程序中,程序中的变量记录与预期值不同?

javascript - OnClick 的蓝色覆盖

javascript - Angular Google Maps - 显示两个数据模型的坐标

javascript - 模块导出多个类

php - xmlHttpRequest 检查 mysql 数据库中的更改

javascript - 避免使用javascript构造?

javascript - AngularJS 表单未重置