简体   繁体   中英

Regex - check string has one or more chars without some chars

I have a string like that

const str = "<p><p><br></p>something</p>";

I want to check if the string has one or more char without <, >, p, /, b, r, (whitespace) . In the above case it should true, because the string has char of s, o, m, e etc

How can do this check ?

You can extract the text from html and check like below:

 function extractContent(s) { var span = document.createElement('span'); span.innerHTML = s; return span.textContent || span.innerText; }; cont = extractContent("<p><p><br></p>something</p>"); if(cont) console.log(cont, true)

You could use lookaround in regex.

Lookahead and lookbehind, collectively called “lookaround”, are zero-length assertions just like the start and end of line, and start and end of word anchors.

Example.

 let regex = /(?<!<)[\\w](?!>)/g; const str = "<p><p><br></p>something</p>"; if(regex.test(str)) { console.log('Yes'); } else { console.log('No'); } console.log('Match: ', str.match(regex).toString());

OR just use simple Character ranges .

 let regex = /[^pbr<>\\/]/g; const str = "<p><p><br></p>something</p>"; if(regex.test(str)) { console.log('Yes'); } else { console.log('No'); } console.log("Match: ", str.match(regex).toString());

I just figure out with lodash's pullAllBy function

let arr = "<p><p><br></p>somebbthing</p>"

const s1 = arr.split('');

let newArr = _.pullAllBy(s1, ['<', '>', '/', 'p', 'b', 'r']);
if(newArr.length > 0) {
  console.log('true');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM