来自表单输入的 Javascript 预测文本 - 显示选项列表并在选择选项时覆盖提示

Javascript predictive text from form input - showing a list of options and overriding the hint when an option has been chosen

提问人:The Old County 提问时间:10/7/2023 最后编辑:The Old County 更新时间:10/7/2023 访问量:56

问:

我正在开发一种预测文本功能,该功能可以分析输入中的文本 - 如果用户即将触发预测通配符以填充提示文本,并在需要时由用户选择进行覆盖。它应该在提示文本下显示可用选项列表。

目前,虽然有故障。在后来的版本中,它重复重复的单词,并且不会覆盖用户的选择。

enter image description here

enter image description here

  function getHint(transcript){
    console.log("GET HINT1");

    let triggerOne = "(?:\\b|')(to)(?:\\b|')";
    const found = transcript.match(triggerOne);
    //let last2 = transcript.slice(-2);
    console.log("found", found);
    //console.log("last2", last2);
    //console.log("found.length", found?.length);

    let hint = "";
    if(found){
    //if(found && (last2 !== "to") ){
      //found?.length > 0
      hint = "<span>jupiter moons</span>";
    }
  
    return transcript + " " +hint;
  }    

另类

  getHint(transcript) {
    // Define an array of dynamic keywords
    const dynamicKeywords = ['to', 'from', 'a']

    // Create a regular expression pattern to match any of the dynamic keywords
    const dynamicKeywordRegex = new RegExp(
      `\\b(${dynamicKeywords.join('|')})\\b`,
      'gi',
    )

    // Find all matches in the input text
    const matches = transcript.match(dynamicKeywordRegex)

    if (matches) {
      const uniqueMatches = [...new Set(matches)] // Remove duplicate matches

      let hints = {} // Create an object to store hints
      uniqueMatches.forEach((match) => {
        hints[match] = this.state.data[match]
      })

      this.setState({
        suggestions: hints, // Update suggestions with the hint object
        transcriptLength: transcript.length,
        transcript: transcript,
      })
    } else {
      this.setState({
        transcriptLength: 0,
      })
    }
  }

  handleChange(data) {
    let transcript = data.command

    // Get the dynamic keywords from your state data
    const dynamicKeywords = Object.keys(this.state.data)
    // Create a regular expression pattern to match any dynamic keyword
    const dynamicKeywordRegex = new RegExp(
      `\\b(${dynamicKeywords.join('|')})\\b`,
      'gi',
    )

    //   // Find all matches in the input text
    const matches = transcript.match(dynamicKeywordRegex)

    if (matches) {
      // Replace all dynamic keywords with highlighting in the transcript
      let highlightedText = transcript.replace(
        dynamicKeywordRegex,
        (match) =>
          ` ${match} <span className="highlighted-text">${this.state.data[match][0].key}</span>`,
      )

      // Set the highlighted text in the ref
      this.myRef.current.innerHTML = highlightedText

      // Update the hinted text
      this.getHint(transcript)
    } else {
      // No dynamic keywords found, reset the highlighting
      this.myRef.current.innerHTML = transcript

      // Update the hinted text
      this.getHint(transcript)
    }
    // Remove duplicates within the ref
    const currentText = this.myRef.current.textContent
    const newText = this.removeDuplicateWordsAcrossSegments(currentText)
    this.myRef.current.textContent = newText

    this.myRef.current.textContent = currentText
  }

第 1 阶段

https://jsfiddle.net/9kxdnpL6/7/

         var to = [
            {
              "key": "home",
              "details": "20 Glenbrook Dr, Hillsborough CA 92591"
            },
            {
              "key": "work",
              "details": "400 S El Camino Real San Mateo, CA 92591"
            }
          ];
          
          var from = [
            {
              "key": "Wimpole Pharmacy",
              "details": "pharmacies"
            },
            {
              "key": "JP Pharmacy",
              "details": "pharmacies"
            },
            {
              "key": "Morrisons Pharmacy",
              "details": "pharmacies"
            }
          ]
        


        function submitLoginForm(event){
            event.preventDefault();

            console.log(event.target['command'].value);
            var transcript = event.target['command'].value;

          var s = document.getElementById("textHolder");
          s.innerHTML = getHint(transcript);
            
        }      
        
        
      
      function getHint(transcript){
        console.log("GET HINT1");

        let triggerOne = "(?:\\b|')(to)(?:\\b|')";
        const found = transcript.match(triggerOne);
        //let last2 = transcript.slice(-2);
        console.log("found", found);
        //console.log("last2", last2);
        //console.log("found.length", found?.length);

        let hint = "";
        if(found){
        //if(found && (last2 !== "to") ){
          //found?.length > 0
          hint = "<span>jupiter moons</span>";
        }
      
        return transcript + " " +hint;
      }    
        
 <form onsubmit="submitLoginForm(event)">
        <input type="text" name="command">
        <input type="submit" value="submit">
    </form>

    <div id="textHolder"></div>

第 2 阶段 - 它查找提示,但复制单词,并且不会覆盖用户的选择。https://codesandbox.io/s/compassionate-elgamal-4h4f2f?file=/src/_globals/PredictiveText/PredictiveText.js:4402-4622

JavaScript HTML ReactJS 正则表达式

评论


答: 暂无答案