Skip to content

str — 字符串工具 ​

str 模块提供了丰富的字符串操作功能,包括判空、查找、大小写转换、裁剪、分割、命名转换、编码、类型转换、格式验证、脱敏等。

引入方式 ​

javascript
var str = require("str")

判空 ​

javascript
str.IsEmpty("")          // true
str.IsNotEmpty("hello")  // true
str.IsBlank("  ")        // true(仅空白字符)
str.IsNotBlank("hello")  // true

包含与查找 ​

javascript
str.Contains("Hello World", "World")    // true
str.IndexOf("Hello World", "World")     // 6
str.LastIndexOf("Hello World", "o")     // 7
str.Count("Hello", "l")                 // 2
str.Length("Hello")                     // 5

大小写转换 ​

javascript
str.ToUpper("hello")         // "HELLO"
str.ToLower("HELLO")         // "hello"
str.FirstUpper("hello")      // "Hello"
str.FirstLower("Hello")      // "hello"
str.Capitalize("hello world") // "Hello world"

裁剪与截取 ​

javascript
str.Trim("  hello  ")                // "hello"
str.TrimLeft("  hello  ")            // "hello  "
str.TrimRight("  hello  ")           // "  hello"
str.Substring("Hello World", 0, 5)   // "Hello"
str.Between("(hello)", "(", ")")     // "hello"
str.Before("Hello World", " World")  // "Hello"
str.After("Hello World", "Hello ")   // "World"

分割与合并 ​

javascript
str.Split("a,b,c", ",")         // ["a", "b", "c"]
str.Join(["a", "b", "c"], ",")  // "a,b,c"

替换 ​

javascript
str.Replace("Hello World", "World", "SSS-RUN")     // "Hello SSS-RUN"
str.ReplaceAll("aabbcc", "b", "x")                   // "aaxxcc"

命名转换 ​

javascript
str.CamelCase("hello_world")    // "helloWorld"
str.SnakeCase("helloWorld")     // "hello_world"
str.KebabCase("helloWorld")     // "hello-world"
str.PascalCase("hello_world")   // "HelloWorld"

编码 ​

javascript
str.MD5("hello")                    // "5d41402abc4b2a76b9719d911017c592"
str.Base64Encode("hello")           // "aGVsbG8="
str.Base64Decode("aGVsbG8=")        // "hello"

类型转换 ​

javascript
str.ToInt("123")          // 123
str.ToInt64("123")        // 123
str.ToFloat64("3.14")     // 3.14
str.ToBool("true")        // true
str.ToString(123)          // "123"

格式验证 ​

javascript
str.IsEmail("test@example.com")   // true
str.IsURL("https://example.com")  // true
str.IsIP("192.168.1.1")           // true
str.IsPhone("13800138000")        // true
str.IsUUID("xxx-xxx-xxx")         // true

脱敏 ​

javascript
str.Mask("13800138000", 3, 4)         // "138****8000"
str.MaskEmail("test@example.com")      // "t***@example.com"
str.MaskPhone("13800138000")           // "138****8000"
str.MaskCard("6222021234567890")       // "6222****7890"

完整示例 ​

javascript
var str = require("str")

// 参数校验
var email = request.Input("email", "")
if (!str.IsEmail(email)) {
    response.Error("邮箱格式不正确")
    return
}

// 命名转换
var columnName = str.SnakeCase("userName")  // "user_name"

// 脱敏处理
var phone = str.MaskPhone("13800138000")    // "138****8000"

// 字符串编码
var hash = str.MD5("password123")

版权所有.