首页 > 解决方案 > JS: Extracting specific text from a string

问题描述

I have a string like this ...

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";

I want to extract all the "unique" lines that start with the word ... "Value" ...

So expected output is ...

Here is what I have tried so far ...

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);

Performance is an issue, so I prefer the most optimized solution.

标签: javascript

解决方案


您可以使用单个正则表达式,不需要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)
);


推荐阅读