代码之家  ›  专栏  ›  技术社区  ›  Lorenzo OnoSendai

如何在javascript/jquery中插入字符串并测试字符串的开头?[副本]

  •  2
  • Lorenzo OnoSendai  · 技术社区  · 14 年前

    可能的重复:
    Splitting in string in JavaScript
    javascript startswith

    你好 我在javascript中有一个字符串,我需要操作它。字符串格式如下

    xxx_yyy
    

    我需要:

    • 再现 string.StartsWith("xxx_") 在c中#
    • 把绳子一分为二 string.Split("_") 在c中#

    有什么帮助吗?

    4 回复  |  直到 8 年前
        1
  •  11
  •   Nick Craver    14 年前

    这里不需要jQuery,只需要简单的JavaScript就可以了 .indexOf() .split() ,例如:

    var str = "xxx_yyy";
    var startsWith = str.indexOf("xxx_") === 0;
    var stringArray = str.split("_");
    

    You can test it out here .

        2
  •  2
  •   Jacob Relkin    14 年前

    干得好:

    String.prototype.startsWith = function(pattern) {
       return this.indexOf(pattern) === 0;
    };
    

    split 已定义为 String 方法,现在可以使用新创建的 startsWith 方法如下:

    var startsWithXXX = string.startsWith('xxx_'); //true
    var array = string.split('_'); //['xxx', 'yyy'];
    
        3
  •  1
  •   Justin Niessner    14 年前

    通过使用JavaScript的 string.indexOf() :

    var startsWith = function(string, pattern){
        return string.indexOf(pattern) == 0;
    }
    

    您可以简单地使用JavaScript string.split() 方法进行拆分。

        4
  •  1
  •   troynt    14 年前

    JavaScript已经分离了内置的。

    'xxx_yyy'.split('_'); //produces ['xxx','yyy']
    
    String.prototype.startsWith = function( str ) {
      return this.indexOf(str) == 0;
    }
    
    
    'xxx_yyy'.startsWith('xxx'); //produces true