Javascript:逐个循环分割字符串

时间:2020-03-25 13:13:02

标签: javascript jquery loops for-loop split

我有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);
    }
  }
}

我不确定这是个好方法

2 个答案:

答案 0 :(得分:3)

使用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>

答案 1 :(得分:1)

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

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