JavaScript之字符串匹配工具[插件]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript之字符串匹配工具[插件]相关的知识,希望对你有一定的参考价值。

/***
     * StringCheckUtil
     * 字符串检测工具
     *
     * @version 1.0
     * @method isNum(string,scope)
     * @method isChinese(string,scope)
     * @method isEnglish(string,scope)
     * @method isContainsString(string,subString,Case)
     */

    /**
     * isNum(string,scope)
     * @param string:string resource 
     * @param scope:all,part
     */
    var StringCheckUtil = function() {};
    StringCheckUtil.prototype.isNum = function(string, scope) {
        //检验参数合法性
        if ((arguments.length != 2) || (typeof(string) != ‘string‘) || (typeof(scope) != ‘string‘)) {
            throw new Error("Arguments is not qualified!");
        }
        //检验scope参数
        if ((scope != ‘part‘) && (scope != ‘all‘)) {
            throw new Error("The argument what named is ‘scope‘ is not qualified!");
        }

        var regex_all = /\d*/; //i忽略大小写
        var regex_part = /\d/gi;

        switch(scope){
            case ‘all‘:
                return (string.match(regex_all) == string) ? true : false;break;
            case ‘part‘:
                return (regex_part.test(string));break;
            default:
                console.log(‘This string is unknown.‘);
        }
    }

    /**
     * isContainsString(string,Case)
     * @param string:string resource 
     * @param Case:i(case-insentitive):忽略大小写,c:(case)不忽略大小写
     * 
     */
    StringCheckUtil.prototype.isContainsString = function(string, subString, Case) {
        //检验参数合法性
        if ((arguments.length != 3) || (typeof(string) != ‘string‘) || (typeof(subString) != ‘string‘) || (typeof(Case) != ‘string‘)) {
            throw new Error("Arguments‘ length is not qualified!");
        }
        //检验scope参数
        if ((Case != ‘i‘) && (Case != ‘c‘)) {
            throw new Error("The argument what named is ‘scope‘ is not qualified!");
        }

        var regex_case = (Case == ‘i‘) ? ‘i‘ : ‘‘;
        var regex_scope = ‘g‘; //默认:全局

        var regex = new RegExp(subString, regex_case + regex_scope);
        return regex.test(string);
    }

 

Demo:

    var string_cs = "89898 67646g 6585dgdf7";
    var stringNum = "jh787kk";
    var Case_cs = ‘i‘;
    var subString_cs = "67646G";
    var stringUtil_cs = new StringCheckUtil();

    console.log("isNum:" + stringUtil_cs.isNum(stringNum, "all"));//非得全部是整数数字(不带小数点)
    console.log("isNum:" + stringUtil_cs.isNum(stringNum, "part"));//包含数字

    console.log("isContainsString:" + stringUtil_cs.isContainsString(string_cs, subString_cs, Case_cs));
    //忽略大小写,是否包含目标字符串

  

未完待续....

以上是关于JavaScript之字符串匹配工具[插件]的主要内容,如果未能解决你的问题,请参考以下文章

Javascript 正则扩展之dotAll模式

Javascript 正则扩展之dotAll模式

JavaScript - 正则表达之二

sublime 插件(侧重JavaScript)

ESLint

JavaScript之基础-10 JavaScript 正则表达式(概述定义正则RegExp对象用于模式匹配的String方法)