过滤唯一的字母集,该字符串从特定字符开始

时间:2019-07-18 11:14:42

标签: javascript regex

我想过滤唯一的字母集,该字符串从特定字符开始。例子

s = "/abc/123a/a123/ab1c/hij/a-b/n98mbd-",

因此,如果使用正则表达式替换,则应返回唯一的字符串,如:

s= "/abc/hij"

应该用“ /”代替其他非字母组。

2 个答案:

答案 0 :(得分:0)

var s = "/abc/123a/a123/ab1c/hij/a-b/n98mbd-";
var s2 = s
  // get every part to process separately
  .split('/')
  // filter not valid parts
  .filter(                  
    // ^ - start check from the very first symbol  
    // [a-z] - allow letters
    // + - there should be at least one letter. empty values are not valid
    // $ - check till the last symbol
    // i - small and capital letters are both ok
    v => /^[a-z]+$/i.test(v)
  )
  // join back into string
  .join('/');

答案 1 :(得分:0)

const s = "/abc/123a/a123/ab1c/hij/a-b/n98mbd-";
const r = (s.match(/\/[a-z]+(?=\/|$)/g) || []).join('');

console.log( r );

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
https://regex101.com/r/7Uah38/1