【问题标题】:Javascript: Split string by loop in loopJavascript:在循环中按循环拆分字符串
【发布时间】:2020-07-06 01:02:27
【问题描述】:

我有一个字符串,其 ID 和名称由 ^(在 ID 和名称之间)和 ; 分隔。 (组间)例如

var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";

我需要这样的东西

$('#1').html('<option value="1">John Smith</option><option value="2">Sophia Williams</option><option value="3">Emily Johnson</option>');

我尝试了循环但卡住了:

var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";

var a = string.split(";"),
    i;
for (i = 0; i < a.length; i++){
  if (a[i] !== ""){
    var b = a[i].split("^"),
    i2;
    for (var i2 = 0; i2 < b.length; i++) {
      var name = b[i2];
      console.log(name);
    }
  }
}

我不确定这是不是好方法

【问题讨论】:

  • 您根本不需要内部循环。只需在需要的地方使用b[0]b[1] 构造字符串。
  • 旁注:jQuery 可以容忍它,但 #1 是一个无效的选择器。 ID 选择器不能以未转义的数字开头。

标签: javascript jquery loops for-loop split


【解决方案1】:

使用Option()

new Option(text, value, defaultSelected, selected)

var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;"

var options = string.split(';').map(i => {
  return new Option(...i.split('^').reverse())
})

$('#1').html(options)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<select id="1"></select>

【讨论】:

  • 尽管它似乎在您的答案中使用的 jQuery 版本中工作,但我会担心依赖将Options 的数组传递给html,它似乎并不成为documented 行为。
  • @T.J.Crowder new Option(...i.split('^').reverse()) 看起来确实很老套,我什至不确定它如何与 ...
  • @mplungjan - 这部分不是问题:它将字符串i 拆分为^(例如,得到["1", "John Smith"]),然后反转该数组并将其展开为Option 构造函数的两个参数(文本和值)。 :-)
  • 啊。因为数组有效 - 我无法以一种我可以相信新选项会喜欢它的方式来 console.log(...i.split('^').reverse())
【解决方案2】:

您可以在循环中构建 HTML 字符串,方法是从 b 中获取第一个元素作为选项的值,从 b 中获取第二个元素作为选项标签中的文本。然后,您可以使用这些文本和值组件将选项标记的字符串 HTML 版本添加到每次 for 循环迭代的累积字符串中:

var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";

var a = string.split(";");
var html_str = "";
for (var i = 0; i < a.length-1; i++) { // loop to a.length-1 so you don't need an if-statement to check blanks
  var b = a[i].split("^");
  var val = b[0];
  var txt = b[1];
  html_str += '<option value="' + val +'">' + txt +'</option>';
}

$('#one').html(html_str);
console.log(html_str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="one"></select>

另一种方法是使用正则表达式从字符串中获取组件,然后使用 .replace() 和替换函数将其转换为所需的 HTML 字符串:

var string = "1^John Smith;2^Sophia Williams;3^Emily Johnson;";
var html_str = string.replace(/(\d+)\^([^;]+);/g, (_, val, txt) => `<option value="${val}">${txt}</option>`);

$('#one').html(html_str);
console.log(html_str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="one">
</select>

上面的正则表达式:

  • (\d+)\^:对后面有克拉 ^ 的任何数字(第 1 组)进行分组
  • ([^;]+);:将非分号;(第 2 组)的任何字符分组,后跟分号。

这些组是针对字符串中的每次出现而形成的,然后在.replace() 方法的回调中使用,其中组 1 是 val,组 2 是 txt

【讨论】:

    猜你喜欢
    • 2014-09-19
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多