【问题标题】:Add a "+" before each word in a string using jQuery使用 jQuery 在字符串中的每个单词前添加一个“+”
【发布时间】:2017-07-19 07:52:30
【问题描述】:

我使用javascript 创建了一个数组“outData”,如下所示:

我现在正在尝试:

  1. 使用 jQuery 循环遍历 outData 数组;
  2. 如果勾选了“bmm”复选框,则将 outData 数组中的字符串拆分为单个单词;
  3. 在每个单词前添加一个“+”号;
  4. 最后,将带有加号的单词连接成新字符串(每个单词之间有一个空格)并压入一个名为“outPlus”的新数组。

我不知道如何在从字符串中拆分出的每个单词之前正确添加加号。

我的代码目前如下所示:

$(document).ready(function() {

    $("#multi").submit(function(e) {
        e.preventDefault();
        $("#output").empty();
        var array1 = [];
        var array2 = [];
        var array3 = [];
        $(".col1").each(function() {
            var word1 = $(this).val();
            if ( word1 !== "" ) {
                //word1 = word1.replace(/\s+/g, '');
                array1.push(word1);
            }
        });
        $(".col2").each(function() {
            var word2 = $(this).val();
            if ( word2 !== "" ) {
                //word2 = word2.replace(/\s+/g, '');
                array2.push(word2);
            }
        });
        $(".col3").each(function() {
            var word3 = $(this).val();
            if ( word3 !== "" ) {
                //word3 = word3.replace(/\s+/g, '');
                array3.push(word3);
            }
        });
        console.log(array1);
        console.log(array2);
        console.log(array3);
        var outData = [];
        var outPlus = [];
        $(array1).each(function( a, b ) {
            $(array2).each(function ( c, d ) {
                outData.push( b + " " + d );
                $(array3).each(function( e, f ) {
                    outData.push( b + " " + d + " " + f );
                });
            });
        });

        console.log(outData);

        if ( $("input[name='bmm']").prop("checked") == true ) {
            $(outData).each(function( g, h ) {
                outPlus.push( h.split(" ") );
            });

            console.log(outPlus);

            $(outPlus).each(function( i, j ) {
                    var output = j.replace(/(^|\s)/g, '$1+');
                    console.log(j);
                });
        }

        console.log(outPlus); //Uncaught TypeError: j.replace is not a function
    });

});

当前输出:

Uncaught TypeError: j.replace is not a function

期望的输出:

+used +car
+used +car +for +sale
+used +car +on +sale
etc...

非常感谢帮助产生预期的结果。非常感谢。

【问题讨论】:

  • outPlus.push( h.split(" ").join("+") );outPlus.push("+"+ h.split(" ").join("+") ); 并删除此 $(outPlus).each(function( i, j ) { console.log("+" + j); //Produces output: "+used,car" etc... });
  • 您的逻辑似乎有点不对劲,但如果没有看到完整的实现,很难提供改进。我在下面的回答至少应该解决您的直接问题。
  • @Anant 这不太对(我不认为)。由此,我得到:“used+car”、“used+car+for+sale”等......

标签: javascript jquery arrays string


【解决方案1】:

@Rory 的替代方法是使用 /(\w+)/g 正则表达式。

想法是捕获所有单词并将它们替换为+$1

获取新数组

var outData = [
  'used car',
  'used car for sale',
  'used car on sale',
  'used cars'
];

var output = outData.map(function(text) {
  return text.replace(/(\w+)/g, '+$1');
});

console.log(output);

替换原数组

var outData = [
  'used car',
  'used car for sale',
  'used car on sale',
  'used cars'
];

outData.forEach(function(text, i, a) {
  a[i] = text.replace(/(\w+)/g, '+$1');
});

console.log(outData);

【讨论】:

  • 我编辑了你的答案,因为第一个 sn-p 输出了错误的数组 :) 我在我的答案中专门使用了 \s 来查找空格,因为 \w 将匹配像 , 或 @ 这样的标点符号987654329@,如果这些值出现在原始数组中。仍然 +1。
【解决方案2】:

要解决此问题,您可以在任何空格字符或字符串中的第一个字符之后使用正则表达式,并带有+。试试这个:

$(outPlus).each(function(i, j ) {
  var output = j.replace(/(^|\s)/g, '$1+');
  console.log(j);
});

这是一个简化的例子:

var outData = [
  'used car',
  'used car for sale',
  'used car on sale',
  'used cars'
];

outData = outData.map(function(text) {
  return text.replace(/(^|\s)/g, '$1+');
});

console.log(outData);

【讨论】:

  • 嗨,Rory - 我确信这确实有效,但我首先创建了 outData 数组的方式。我收到一个错误:“未捕获的 TypeError:j.replace 不是函数”。我要粘贴我的完整代码 sn-p 吗?
  • 请。查看更完整的代码示例会非常有帮助,包括如何在步骤 1 中创建 DOM 元素
  • 请在您的问题上使用edit按钮添加相关代码
  • 该错误似乎是因为您已将outPlus 构建为多维数组,因此j 是一个数组,而不是字符串,因此出现错误。我什至不确定您为什么要这样做,因为outPlus 似乎没有任何用处。
  • 我这样构建它是因为它是我知道(知识有限)以这种特定方式连接三列单词(.col1、.col2、.col3)的唯一方法。 outPlus 旨在用于保存从 outData 数组中拆分出来的单词,同时添加加号。我很乐意将字符串从 outData 中拆分出来,添加加号,然后如果您知道如何输出它们?
【解决方案3】:

需要在split() 之后立即使用join() 将您的数组与+ 符号连接起来,如下所示(简单)。

var outData = ['used car', 'used car for sale', 'used car on sale'];
   
var outPlus = [];

$(outData).each(function( g, h ) {
    outPlus.push("+"+h.split(" ").join(' +'));
});
console.log(outPlus);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

  • 缺少解释。 -1
  • 另外,最好使用内置的循环机制。 Array.forEachArray.map 应该这样做
  • @Anant 这解决了最初的问题,尽管我的代码很糟糕。干杯阿南特。
  • @jonhendrix 很高兴为您提供帮助。
【解决方案4】:

您可以在最后一个 console.log 行上输出它,这会快速将输出更改为您想要的:

console.log('+used,car,on,sale'.replace(/,/g, ' +'))

它基本上将逗号替换为空格和+,它既快速又简单,否则我会使用.split 方法并拆分逗号所在的位置并从返回的数组中重新构建。

【讨论】:

    【解决方案5】:

    jquery 没用,试试这个:

    如果您不想要es6 函数语法=>,您可以随时使用旧的function

    const data = [
      'used car',
      'used car for sale and something else'
    ]
    
    const addPlus = data => data.replace(/\+?(\S+)/g, '+$1')
    
    const addPlusInArray = array => array.map(addPlus)
    
    console.log(addPlusInArray(data))

    .replace(
    /\+?(\S+)/g 查找任何非空格(可选 + 前面)
    '+$1' 替换为第一个捕获组的内容
    )

    .map (
    addPlus第一个参数作为数组元素调用的函数结果将成为新数组的新内容
    )

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2018-03-08
      • 2017-07-25
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      相关资源
      最近更新 更多