douka19950505 2013-10-07 19:57
浏览 111
已采纳

如何将字符串编码的PHP正则表达式转换为JS正则表达式?

I have a very simple regex that I am using for highlighting search terms in my application. If a user types in 'stack' into the search form, for example, the following regular expression is used as a string argument for preg_match_all to highlight the results:

"/\b((stack|stacks))\b/i"

I am using json_encode to output some of my configuration options for my application, including the regex above. I need this regex on the client-side because I am lazy-loading pagination items in an infinite-scroll fashion, and I want to take advantage of the client-side to parse the HTML for the proper search term highlighting.

My JS configuration object now appears similar to:

config = {
   searchRegex: "/\b((stack|stacks))\b/i",
   // ... more options
}

If searchRegex wasn't a string, I wouldn't have a problem. It would automatically be a regular expression object, and there is nothing in that regex that JavaScript doesn't support. But now, I have to resort to parsing the string to get the appropriate arguments for the RegExp constructor, which involves removing the delimiters and getting the modifier(s). With all the escaped characters that could be present, this doesn't seem like a viable or sane option.

How would I convert searchRegex to become a regular expression object?

  • 写回答

4条回答

  • doupi3874 2013-10-07 22:17
    关注

    Thanks for your answers. I decided to output the regex-based string sans modifiers and delimiters to the client and use JS to pass it and the separated modifier to the RegExp constructor. Ended up with something similar to:

    config = {
        searchRegex: '\b((stack|stacks))\b',
        modifiers: 'i'
    }
    
    // ... later
    model.initialize = function () {
        config.searchRegex = new RegExp(config.searchRegex, config.modifiers || '');
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果