0

I need to write a JS RegExp that will match word based on the exclusion of set chars: [', ", -, _ ] so bolded words should be matched only from my example:

Milan some word, milan again.Milan word - again: Milan, milan-milan. Milan-word milan is word.milan mialn . milan's milan"s, milan milan_milan.

Note: I don't want to include spaces, dots, commas, before/after word milan and therefore I need to get result same as I bolded it above.

I need it to work like: \bmilan\b but i need to exclude set of chars so it doesn't match examples like milan-milan and milan's at all.

I tried to make it work: https://regex101.com/r/FGeNlQ/1 but it isn't complete. In this example spaces, dots, etc... are included in matched word and I don't want that.

Sorry if this may be duplicate but i just can't find right answer

EDIT:

code usage:

window.wrapText = (sentence, word, description) ->
    regex = "(?:[^\"'`_-]|^)\\b(" + word + ")\\b(?![\"'`_-])"
    re = new RegExp(regex, 'gi')
    span = document.createElement('span')
    span.innerHTML = sentence

    Array.from span.childNodes, (node) =>
      if node.nodeType == 3
        node.nodeValue.split(re).forEach (part, i) ->
          add = undefined
          if i % 2
            add = document.createElement('span')
            add.textContent = part
            add.setAttribute('class', 'glossary_text')
          else
            add = document.createTextNode(part)
          span.insertBefore add, node

        span.removeChild node

    span.innerHTML

note: i may have not escaped well 'regex' variable

  • [`(?:[^"'\`_-]|^)\b(milan)\b(?!["'\`_-])`](https://regex101.com/r/3S0uhH/1) should be enough. Add necessary logic to get the capturing group 1 values. – Wiktor Stribiżew Oct 24 '17 at 12:12
  • @WiktorStribiżew yes but this will include , and spaces in front of word – user7754069 Oct 24 '17 at 12:18
  • It does not matter if anything is "included", the structure of the match object provides enough details for you to write custom post-processing logic, which we cannot you help with as you have not shared any further details about what you are doing (replacing, extracting, wrapping....). Also, please post your code if you need help. – Wiktor Stribiżew Oct 24 '17 at 12:21
  • @WiktorStribiżew i am trying to find that word and wrap in new tag, so that is reason why i dont to wrap .Milan but just Milan – user7754069 Oct 24 '17 at 13:02
  • @WiktorStribiżew i posted this question which u marked as duplicate even if it is not: https://stackoverflow.com/questions/46816258/js-regexp-finding-word-that-is-not-in-tag-and-replace-string i am trying to exclude specific tag with specific class. – user7754069 Oct 24 '17 at 13:03
  • Please post the code you have now. Other question details are irrelevant. – Wiktor Stribiżew Oct 24 '17 at 13:07
  • @WiktorStribiżew ok i will edit question – user7754069 Oct 24 '17 at 13:22

0 Answers0