Search code examples
draftjs

How to check if a phrase is contained in the contentState?


I'm trying to figure out if a certain phrase (it can contain a newlines or bullet points) is contained in the contentState of an editor instance.

How do I lookup if a text (“the lazy fox jumped\n over the \n• lazy dog”) is contained in the editorState?

Is there a helper/util method to do such task?

Can I get the offset of such a match?


Solution

  • How do I lookup if a text (“the lazy fox jumped\n over the \n• lazy dog”) is contained in the editorState? Is there a helper/util method to do such task?

    One method would be to search the content string:

     editorState
      .getCurrentContent()
      .getPlainText()
      .search("your phrase") // -> index of match or -1
    

    getPlainText() has an optional delimiter argument if that helps shape the content - and of course there are various string methods at your disposal as well as regex.