 | |  |  | AIWROK软件String实例演示
- /*
- 🍎交流QQ群711841924群一,苹果内测群,528816639
- 🍎🔨JavaScript字符串工具类封装
- 🔨适用本文档ES5系统安卓 JavaScript引擎Rhino
- */
- /**
- * 字符串工具类封装
- * 提供更加面向对象的字符串操作接口
- */
- function StringUtils() {}
- /**
- * 返回指定位置的字符
- * @param {string} str - 源字符串
- * @param {number} index - 字符位置
- * @returns {string} 指定位置的字符
- */
- StringUtils.prototype.charAt = function(str, index) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (typeof index !== 'number' || index % 1 !== 0) throw new Error('[错误] 参数index必须是整数');
- return str.charAt(index);
- };
- /**
- * 返回指定位置字符的Unicode编码
- * @param {string} str - 源字符串
- * @param {number} index - 字符位置
- * @returns {number} Unicode编码值
- */
- StringUtils.prototype.charCodeAt = function(str, index) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (typeof index !== 'number' || index % 1 !== 0) throw new Error('[错误] 参数index必须是整数');
- return str.charCodeAt(index);
- };
- /**
- * 查找子字符串首次出现的位置
- * @param {string} str - 源字符串
- * @param {string} searchValue - 要查找的子字符串
- * @param {number} [fromIndex=0] - 开始查找的位置
- * @returns {number} 首次出现的位置,未找到返回-1
- */
- StringUtils.prototype.indexOf = function(str, searchValue, fromIndex) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (typeof searchValue !== 'string') throw new Error('[错误] 参数searchValue必须是字符串');
- return str.indexOf(searchValue, fromIndex);
- };
- /**
- * 查找子字符串最后一次出现的位置
- * @param {string} str - 源字符串
- * @param {string} searchValue - 要查找的子字符串
- * @param {number} [fromIndex=str.length] - 开始查找的位置
- * @returns {number} 最后一次出现的位置,未找到返回-1
- */
- StringUtils.prototype.lastIndexOf = function(str, searchValue, fromIndex) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (typeof searchValue !== 'string') throw new Error('[错误] 参数searchValue必须是字符串');
- return str.lastIndexOf(searchValue, fromIndex);
- };
- /**
- * 获取字符串长度
- * @param {string} str - 源字符串
- * @returns {number} 字符串长度
- */
- StringUtils.prototype.getLength = function(str) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- return str.length;
- };
- /**
- * 使用正则表达式匹配字符串
- * @param {string} str - 源字符串
- * @param {RegExp} regexp - 正则表达式
- * @returns {Array|null} 匹配结果数组,未匹配返回null
- */
- StringUtils.prototype.match = function(str, regexp) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (!(regexp instanceof RegExp)) throw new Error('[错误] 参数regexp必须是正则表达式对象');
- return str.match(regexp);
- };
- /**
- * 替换第一个匹配的子字符串
- * @param {string} str - 源字符串
- * @param {string|RegExp} searchValue - 要替换的内容
- * @param {string|Function} replaceValue - 替换内容
- * @returns {string} 替换后的新字符串
- */
- StringUtils.prototype.replace = function(str, searchValue, replaceValue) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- return str.replace(searchValue, replaceValue);
- };
- /**
- * 替换所有匹配的子字符串
- * @param {string} str - 源字符串
- * @param {string|RegExp} searchValue - 要替换的内容
- * @param {string|Function} replaceValue - 替换内容
- * @returns {string} 替换后的新字符串
- */
- StringUtils.prototype.replaceAll = function(str, searchValue, replaceValue) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
-
- // 兼容低版本环境:若不支持replaceAll,用正则/g替代
- if (!String.prototype.replaceAll) {
- if (typeof searchValue === 'string') {
- // 字符串转正则(转义特殊字符)
- var escaped = searchValue.replace(/[.*+?^${}()|[\]\\]/g, '\\[ DISCUZ_CODE_0 ]amp;');
- return str.replace(new RegExp(escaped, 'g'), replaceValue);
- } else if (searchValue instanceof RegExp && !searchValue.global) {
- // 正则无/g修饰符,添加后匹配所有
- var flags = 'g';
- if (searchValue.ignoreCase) flags += 'i';
- if (searchValue.multiline) flags += 'm';
- var newRegexp = new RegExp(searchValue.source, flags);
- return str.replace(newRegexp, replaceValue);
- }
- }
- return str.replaceAll(searchValue, replaceValue);
- };
- /**
- * 分割字符串为数组
- * @param {string} str - 源字符串
- * @param {string|RegExp} separator - 分隔符
- * @param {number} [limit] - 限制返回数组大小
- * @returns {Array} 分割后的字符串数组
- */
- StringUtils.prototype.split = function(str, separator, limit) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- return str.split(separator, limit);
- };
- /**
- * 判断字符串是否以指定内容开头
- * @param {string} str - 源字符串
- * @param {string} searchValue - 要检测的内容
- * @param {number} [position=0] - 检测开始位置
- * @returns {boolean} 是否以指定内容开头
- */
- StringUtils.prototype.startsWith = function(str, searchValue, position) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (typeof searchValue !== 'string') throw new Error('[错误] 参数searchValue必须是字符串');
-
- // 兼容低版本环境:手动实现startsWith
- if (!String.prototype.startsWith) {
- var pos = position || 0;
- return str.substr(pos, searchValue.length) === searchValue;
- }
- return str.startsWith(searchValue, position);
- };
- /**
- * 从指定位置截取指定长度的子字符串
- * @param {string} str - 源字符串
- * @param {number} start - 开始位置
- * @param {number} [length] - 截取长度
- * @returns {string} 截取的子字符串
- */
- StringUtils.prototype.substr = function(str, start, length) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (typeof start !== 'number' || start % 1 !== 0) throw new Error('[错误] 参数start必须是整数');
- return str.substr(start, length);
- };
- /**
- * 截取指定范围的子字符串
- * @param {string} str - 源字符串
- * @param {number} start - 开始位置
- * @param {number} [end] - 结束位置(不包含)
- * @returns {string} 截取的子字符串
- */
- StringUtils.prototype.substring = function(str, start, end) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- if (typeof start !== 'number' || start % 1 !== 0) throw new Error('[错误] 参数start必须是整数');
- return str.substring(start, end);
- };
- /**
- * 去除字符串首尾空白字符
- * @param {string} str - 源字符串
- * @returns {string} 去除首尾空白字符后的字符串
- */
- StringUtils.prototype.trim = function(str) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
-
- // 兼容低版本环境:手动实现trim
- if (!String.prototype.trim) {
- return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
- }
- return str.trim();
- };
- /**
- * 转换字符串为大写
- * @param {string} str - 源字符串
- * @returns {string} 转换后的大写字符串
- */
- StringUtils.prototype.toUpperCase = function(str) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- return str.toUpperCase();
- };
- /**
- * 转换字符串为小写
- * @param {string} str - 源字符串
- * @returns {string} 转换后的小写字符串
- */
- StringUtils.prototype.toLowerCase = function(str) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- return str.toLowerCase();
- };
- /**
- * 连接字符串
- * @param {string} str - 源字符串
- * @param {...string} strings - 要连接的字符串
- * @returns {string} 连接后的字符串
- */
- StringUtils.prototype.concat = function(str) {
- if (typeof str !== 'string') throw new Error('[错误] 参数str必须是字符串');
- var args = Array.prototype.slice.call(arguments, 1);
- return str.concat.apply(str, args);
- };
- // 创建全局实例,方便直接调用
- var StrUtil = new StringUtils();
- // ===============================
- // 使用示例
- // ===============================
- function printl() {
- // 适配打印函数:定义printl用于输出
- var args = Array.prototype.slice.call(arguments);
-
- // 若环境支持console.log直接调用,若不支持可替换为其他输出方式
- if (typeof console !== 'undefined' && console.log) {
- console.log.apply(console, args);
- } else {
- // 降级处理:拼接字符串输出(适配无console环境)
- var output = args.join(' ');
- if (typeof document !== 'undefined') {
- document.write(output + '<br>');
- } else if (typeof process !== 'undefined' && process.stdout) {
- // Node.js或其他环境兜底
- process.stdout.write(output + '\n');
- }
- }
- }
- printl("=== 🚀 字符串工具类封装 - 使用示例 ===");
- var testStr = " Hello, JavaScript World! ";
- printl("基础测试字符串:'" + testStr + "'(含两端空格)");
- printl("---------------------------------------------\n");
- // 示例调用
- printl("1. 获取字符串长度:");
- printl(" StrUtil.getLength('" + testStr + "') => " + StrUtil.getLength(testStr));
- printl("\n2. 获取指定位置字符:");
- printl(" StrUtil.charAt('" + testStr + "', 7) => '" + StrUtil.charAt(testStr, 7) + "'");
- printl("\n3. 查找子字符串位置:");
- printl(" StrUtil.indexOf('" + testStr + "', 'JavaScript') => " + StrUtil.indexOf(testStr, 'JavaScript'));
- printl("\n4. 替换字符串:");
- printl(" StrUtil.replace('" + testStr + "', 'JavaScript', 'JS') => '" + StrUtil.replace(testStr, 'JavaScript', 'JS') + "'");
- printl("\n5. 全部替换:");
- printl(" StrUtil.replaceAll('" + testStr + "', 'l', 'L') => '" + StrUtil.replaceAll(testStr, 'l', 'L') + "'");
- printl("\n6. 字符串分割:");
- var parts = StrUtil.split(testStr, ' ');
- printl(" StrUtil.split('" + testStr + "', ' ') => " + JSON.stringify(parts));
- printl("\n7. 去除首尾空格:");
- printl(" StrUtil.trim('" + testStr + "') => '" + StrUtil.trim(testStr) + "'");
- printl("\n8. 转换大小写:");
- printl(" StrUtil.toUpperCase('" + StrUtil.trim(testStr) + "') => '" + StrUtil.toUpperCase(StrUtil.trim(testStr)) + "'");
- printl(" StrUtil.toLowerCase('" + StrUtil.trim(testStr) + "') => '" + StrUtil.toLowerCase(StrUtil.trim(testStr)) + "'");
- printl("\n9. 判断是否以某字符串开头:");
- printl(" StrUtil.startsWith('" + testStr + "', ' Hello') => " + StrUtil.startsWith(testStr, ' Hello'));
- printl("\n10. 字符串连接:");
- printl(" StrUtil.concat('Hello', ' ', 'World', '!') => '" + StrUtil.concat('Hello', ' ', 'World', '!') + "'");
- printl("\n=== ✅ 字符串工具类封装示例运行完毕 ===");
复制代码
| |  | |  |
|