【问题标题】:jquery find / replace arrays?jquery 查找/替换数组?
【发布时间】:2023-04-02 09:37:01
【问题描述】:

我正在尝试学习如何使用 jQuery 进行模式匹配,但我有一个问题......

在 php 中,我可以这样做:

$find = array("-", "_", "+");
$replace = array("X", "Y", "Z");

$string = "The alphabet ends in -, _, +";
$newstring = str_replace($find, $replace, $string); 

这将产生:字母表以 X、Y、Z 结尾

有没有办法用 jquery 完成这个?我可以在哪里定义一个值数组来搜索并用另一个数组中的值替换它们?我知道我可以做一个替换(/pattern/,“Something”),但希望有一种方法可以在 jquery 中复制这个 php 代码?

【问题讨论】:

    标签: jquery arrays replace


    【解决方案1】:

    这里是副本

    function str_replace (search, replace, subject, count) {
        var i = 0,
            j = 0,
            temp = '',
            repl = '',
            sl = 0,
            fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = Object.prototype.toString.call(r) === '[object Array]',
            sa = Object.prototype.toString.call(s) === '[object Array]';
        s = [].concat(s);
        if (count) {
            this.window[count] = 0;
        }
    
        for (i = 0, sl = s.length; i < sl; i++) {
            if (s[i] === '') {
                continue;
            }
            for (j = 0, fl = f.length; j < fl; j++) {
                temp = s[i] + '';
                repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
                s[i] = (temp).split(f[j]).join(repl);
                if (count && s[i] !== temp) {
                    this.window[count] += (temp.length - s[i].length) / f[j].length;
                }
            }
        }
        return sa ? s : s[0];
    }
    
    str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    
    Output >> 'hemmo, mars'
    

    看看http://phpjs.org/functions/str_replace:527

    【讨论】:

      【解决方案2】:

      here

      String.prototype.replaceArray = function(find, replace) {
        var replaceString = this;
        var regex; 
        for (var i = 0; i < find.length; i++) {
          regex = new RegExp(find[i], "g");
          replaceString = replaceString.replace(regex, replace[i]);
        }
        return replaceString;
      };
      
      var textarea = $(this).val();
      var find = ["<", ">", "\n"];
      var replace = ["&lt;", "&gt;", "<br/>"];
      textarea = textarea.replaceArray(find, replace);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-26
        • 1970-01-01
        • 2021-06-01
        • 2016-03-04
        • 2016-12-29
        • 2012-09-22
        • 2021-10-25
        • 2020-08-23
        相关资源
        最近更新 更多