【问题标题】:What is the best way to get a part of a string from a given string using javascript使用javascript从给定字符串中获取部分字符串的最佳方法是什么
【发布时间】:2015-07-02 13:05:03
【问题描述】:

我在 JavaScript 中有一个这样的字符串:

var str = "1:A;2:B;3:A;4:c;5:D";

如何检索2前面的选项,即B

目前正在使用 for 循环通过将字符串拆分为每个 ; 来实现此目的, 但我想知道是否有更好的方法可以在不使用循环概念的情况下实现这一点。

【问题讨论】:

  • 为什么,循环“概念”有什么问题?
  • 我的字符串可能包含 2000 个“;” , 所以我认为循环遍历 2000 个元素需要一些时间
  • "1:A;2:B;3:A;4:c;5:D".match(/2\:([A-Za-z]+?)\;/)[1];
  • @KeerthiKumar 无论您做什么,计算机都会循环遍历该字符串,即使您在代码中看不到它,javascript 也会在某个时候在内部执行此操作。循环 2000 次对计算机来说没什么大不了的。
  • @HamzaKubba 首先,我的回答对我来说很好。其次,循环遍历 2000 个项目可能并不慢,但 OP 似乎觉得它效率低下,如果有另一种选择。我会使用我得到的正则表达式

标签: javascript jquery regex


【解决方案1】:

正则表达式

var num = '2';
"1:A;2:B;3:A;4:c;5:D".match((new RegExp(num+"\\:([\\S\\s]+?)\\;", "")))[1];

Fiddle

这使用 RegExp (正则表达式) 它的作用是在字符串中查找“2”,然后获取与之关联的选项

子字符串

我想不出更好的词,所以请原谅我。您可以使用子字符串和 .indexOf()

var num = '2',
    string = "1:A;2:B;3:A;4:c;5:D",
    index = string.indexOf(num+':');
string.substring(index+num.length+1,index+num.length+2);

Fiddle

类似

子字符串的答案更容易理解,但下面的答案是一样的ish

var num = '2',
    string = "1:A;2:B;3:A;4:c;5:D";

string[string.indexOf(num+':')+num.length+1];

Fiddle

万无一失

这应该适用于大多数情况。 如果长度超过一个字母,这也将获得选项

var string = "1:A;2:B;3:A;4:c;5:D",
    num = '2',
    result;

if (string.indexOf(';'+num+':') < 0) {
    result = string.match(new RegExp(num+"\\:([\\S\\s]+?)\\;", ""))[1];
} else {
    result = string.match((new RegExp('\\;'+num+"\\:([\\S\\s]+?)\\;", "")))[1];
}

更短:

var string = "1:A;2:B;3:A;4:c;5:D", num = '2', result = string.indexOf(";"+num+":") < 0? string.match(new RegExp(num+"\\:([\\S\\s]+?)\\;",""))[1] : string.match(new RegExp("\\;"+num+"\\:([\\S\\s]+?)\\;",""))[1];

alert(result);

Fiddle (我已经把它做成了单线)

【讨论】:

  • 如果您检查 string.indexOf () 是否为 21 也会返回一些值仪式?因为数字 2 也出现在 21 中
  • @KeerthiKumar 这取决于,这将返回文本'21'在文本中的位置
  • 想象你的字符串是 1:A;20:B;10:A;21:B;2:C;22:A;现在如果你做 string.indexOf (2) 会返回正确的值吗??
  • @KeerthiKumar 你需要 string[string.indexOf(';2:')+2] 你可以使用我的万无一失的方法,让你想要的数字。这将在 100% 的时间内有效
【解决方案2】:

可能是递归方法可以帮助你。

var str = "1:A;2:B;3:A;4:c;5:D",
    arr = str.split(";"),
    len = arr.length;

function getVal(len){
  if(len !== 0){
    getVal(len-1);
    if(arr[len-1].indexOf(2) === 0){
      console.log(arr[len-1].split(":")[1])
    };
  };
};

getVal(len);

【讨论】:

    【解决方案3】:

    如果您想获得 2 前面的选项,您可以使用:

    1. 一个循环(我的首选)
    2. indexOf

    Javascript:

     function getAnswer(str) {
    
       var position = str.indexOf(';2:')
    
       // not found in string, or '2' is the first answer
       if(position === -1) {
         return;
       }
    
       return str.substring(position - 1, position)
     }
    

    【讨论】:

    • 如果字符串以 2:B 开头,那么将没有以前的答案。是的,你可以更优雅地失败。我会更新
    【解决方案4】:

    如果你知道这将是一个模式,你可以使用类似的东西:

    var str = "1:A;2:B;3:A;4:c;5:D";
    var i = 2;
    console.log(str[str.indexOf(i)+2]);
    //Output "B"

    【讨论】:

    • 这完全没用……如果他提前知道模式,那么他可以console.log('B');
    • @HamzaKubba:他可以知道会有一个索引,想知道哪个字母与索引相关联,所以并不是你想的那样没用
    • 他可以,在另一个宇宙中......如果你读到他的问题,那不是他想要的。
    • @HamzaKubba:他没有说字符串的格式,如果是有序的,如果是;分隔,请仔细阅读我的答案,因为不一样console.log('B')
    【解决方案5】:

    循环没有错,最终即使您的代码没有循环,计算机上的某些东西也必须循环字符串才能执行此操作。无论如何,如果您不想在代码中循环,您可以这样做:

    var str, new_str, start_position, end_position, final_result;
    str = "1:A;2:B;3:A;4:c;5:D"; // or another similar string
    new_str = ";" + str + ";" // add at the beginning and end, in case the string starts or ends with 2:SOMETHING, we still want to find it with indexOf below
    start_position = new_str.indexOf(";2:");
    if (start_position > -1) { // we found a 2
      start_position = start_position + 3; // move past the ";2:"
      end_position = new_str.indexOf(";", start_position); // first ";" after the start_position
      final_result = new_str.substring(start_position, end_position);
    }
    

    不过,这仍然是循环,因为indexOf() 在内部使用了循环。循环并没有错,几乎所有编写的程序都至少有一个循环。

    【讨论】:

      【解决方案6】:

      你可以使用split函数,如下;

      var str = "1:A;2:B;3:A;4:c;5:D";
      var result = str.split(":");
      
      document.getElementById("Location").innerHTML = res[2];
      

      【讨论】:

      • 如果他知道号码在哪里,那么他就可以document.getElementById("Location").innerHTML = 'B';
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      相关资源
      最近更新 更多