String遍历方法
for循环
获取字符对应的charCode
let from = '/lerna/cli.js';
'/lerna/cli.js'.charCodeAt(from.length-1); //115 字符s对应charCode
- node内置库
Module._nodeModulePaths用法
/**
* 循环路径,给每一级/后面添加'node_modules'形成一个数组
* '/test/lerna/cli.js' => ['/test/lerna/node_modules','/test/node_modules']
*/
const CHAR_FORWARD_SLASH = 47;
const nmChars = [115,101,108,117,100,111,109,95,101,100,111,110] //node_modules倒叙charCode => [s,e,l,u,d,o,m,_,e,d,o,n]
const nmLen = nmChars.length;
Module._nodeModulePaths = function(from) {
from = path.resolve(from);
if (from === '/')
return ['/node_modules'];
const paths = [];
// 关键算法代码
for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) {
const code = from.charCodeAt(i);
if (code === CHAR_FORWARD_SLASH) {
if (p !== nmLen)
paths.push(from.slice(0, last) + '/node_modules');
last = i;
p = 0;
} else if (p !== -1) {
if (nmChars[p] === code) {
++p;
} else {
p = -1;
}
}
}
paths.push('/node_modules');
return paths;
};
String根据下标查找字符
str.CharAt(index);- 如果存在返回对应字符
- 如果不存在返回
'';
str[index]- 如果存在返回对应字符
- 如果不存在返回
undefined;
'abc'.charAt(1); //b
'abc'[1]; //b
根据字符查找下标
str.indexOf(char)
-
返回值
- 对应的下标
- 找不到返回
undefined
-
使用方法
'/xxx/yyy'.indexOf('/') //0
// 如果想查找第二个/
'/xxx/yyy'.indexOf('/',1) //4 表示跳过第一个/
读nodejs fs内置库realpath方法就用到了这种用法。
字符串截取(根据下标截取字符串)
slice(startIndex,endIndex)
- 如果只传一个参数则从参数位置截取到最后.同数组slice方法
- 如果从后向前截取,startIndex一定要小于endIndex;
'hello world'.slice(-5,-4)
str.substring(startIndex,[endIndex])
- 注意:
- 如果startIndex小于0,或为NaN,则为0
- 如果startIndex大于endIndex则参数调换
- endIndex大于str.length则等于str.length
- endIndex不传则到最后
function formatNumber(val: number) {
if (isNaN(val)) return;
const str = `${(val / 100).toFixed(2)}`;
const intSum = str
.substring(0, str.indexOf('.'))
.replace(/\B(?=(?:\d{3})+$)/g, ',');
const dot = str.substring(str.length, str.indexOf('.')); // indexStart大于indexEnd则相当于参数调换
const ret = intSum + dot;
return ret;
}
subString(startIndex,endIndex)
var str = '12.01';
str.substring(0,str.indexOf('.')) //获取整数部分
str.substring(str.length,str.indexOf('.')) //获取小数部分
String大小写转换
let str = 'Hello Javascript'
str.toLocaleLowerCase() 转小写
str.toLocaleUpperCase() 转大写
String拼接
-
'a' + 'b'运算符拼接 -
模版字符串变量的拼接
-
str.concat(char1,[char2...])拼接字符串 -
str.padEnd(length,char): 从右向左填充 -
str.padStart(length,char): 从左向右填充 -
str.repeat(count): 重复填充
判断是否包含某个字符
str.includes(searchStr)str.indexOf(searchStr)返回下标,-1str.lastIndexOf(searchStr)str.endsWith(searchStr,[length])是否以searchStr结尾;返回true/false
字符串转数组
- str.split(str/regexp) 返回删掉分隔符后的数组
- 注意:
- split(' ') 以空格分隔的数组
- split('') 每个子字符的数组
- split() 整个字符数组
var str = 'hello world';
str.split(' ') //['hello', 'world']
str.split('') //["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
str.split() //['hello world']
字符串增删改查总结
- 增
- repeat
- padEnd
- padStart
- 删
- split(删分隔符)
- trim(删空格)
- 改
- str.replace
- 查
- search
- test
- charAt
- str[i]
- slice
- endsWith
- includes
- lastIndexOf
- typeOf
- subString
- ...
RegExp 字符串对象
-
针对正则匹配 资料
-
常用
- 构造函数形式 new RegExp(/^[0-9]*$/, 'g')
- 字面量形式 /^[0-9]\d*$/g
判断是否匹配正则表达式:
- /regexp/.test('str') 正则判断 ; 返回true/false
- str.search(regex) 返回找到的索引/,-1
- str.trim() 去除空格
- str.match(regexp) 返回匹配到字符串信息的数组
- str.replace(regexp/newSubStr,newSubStr/fn) 替换
| 元字符 | |
|---|---|
| . | 匹配任意字符 |
| {m,n} | 匹配出现m到n次的字符'hello wohhrld'.match(/h{1,5}/g);匹配了["h", "hh"] ;可以省略第二个参数。 例如,[0-9]{2,} 匹配至少两位 0~9 的数字。 |
| [] | 匹配字符集[tT],匹配t或者T |
| [^] | 反向匹配不包含字符集[tT],匹配t或者T以外的字符 |
| * | 前一项出现零次或者多次 {0,n} |
| + | 前一项出现一次或者多次 {1,n} |
| ? | 前一项出现零次或者一次 {0,1} |
| 匹配以...开头的字符 | |
| $ | 匹配以...结尾的字符 |
| \d | 数字 ; /^[0-9]\d*&/ 匹配整数 |
| \D | 非数字,\d的反义 |
| \s | 匹配一个空白字符 |
| \S | 反义的\s |
str.match
node内置库中一个使用方式:
// This only applies to requests of a specific form:
// 1. name/.*
// 2. @scope/name/.*
const EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^./\\%][^/\\%]*)(\/.*)?$/;
function resolveExports(nmPath, request) {
// The implementation's behavior is meant to mirror resolution in ESM.
const [, name, expansion = ''] =
StringPrototypeMatch(request, EXPORTS_PATTERN) || [];
if (!name) {
return false;
}
面试题
将url转换为JSON格式:
将URL转换为JSON格式:想要截取字符串使用字符串的API,substring+indexOf
function parseQueryString(url) {
var obj = {};
var keyvalue = [];
var key = "",
value = "";
var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
for (var i in paraString) {
keyvalue = paraString[i].split("=");
key = keyvalue[0];
value = keyvalue[1];
obj[key] = value;
}
return obj;
}