首页 > 编程语言 >javascript 高级编程系列 - 字符串

javascript 高级编程系列 - 字符串

时间:2022-11-29 17:12:16浏览次数:33  
标签:编程 匹配 log 正则表达式 javascript console str 字符串 const

1. 字符串中的方法

  • match

str.match(reg)

参数: 一个正则表达式对象,如果reg不是正则表达式对象,则会利用new RegExp(reg) 隐式转换。
返回值:
  1. 正则表达式中如果有g标志,则将返回与完整正则表达式匹配的所有结果,但不会返回捕获组。
  2. 正则表达式中如果没有使用g标志,则仅返回第一个完整匹配及其相关的捕获组(Array)。
     并且返回的项目具有如下的属性。
     - groups:一个命名捕获组对象,其键是捕获组名称,值是捕获组,如果未命名捕获组,则为undefined。
     - index: 匹配结果的开始位置
     - input:搜索的字符串
  3. 如果未找到匹配,则返回null
/** 具有g标志的match方法 **/
const str = 'For more information, see Chapter 3.4.5.1';
const re = /see (chapter \d+(\.\d)*)/gi;
const found = str.match(re);
console.log(found); // [ 'see Chapter 3.4.5.1' ]  // 所有匹配

/** 没有g标志的match方法 **/
const str = 'For more information, see Chapter 3.4.5.1';
const re = /see (chapter \d+(\.\d)*)/i;
const found = str.match(re);
console.log(found); 
// out put blow
[
  'see Chapter 3.4.5.1', //  所有匹配的第一项
  'Chapter 3.4.5.1',    // 第一个捕获组匹配的值
  '.1',  // 第二个捕获组捕获的最后一个值
  index: 22, // 是整个匹配从0开始的索引
  input: 'For more information, see Chapter 3.4.5.1', // 被解析的原始字符串
  groups: undefined
]
  • matchAll

str.matchAll(reg)


参数: 一个正则表达式对象,如果reg不是正则表达式对象,则会利用new RegExp(reg) 隐式转换。
       而且正则表达式必须是设置了全局模式g的正则表达式,否则会抛出异常TypeError。
返回值: 一个迭代器
const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';
const array = [...str.matchAll(regexp)]; // convert to array
console.log(array[0]);  // expected output: Array ["test1", "e", "st1", "1"]
console.log(array[1]);  // expected output: Array ["test2", "e", "st2", "2"]

注意: 如果只是得到所有的匹配项则使用str.match(pattern/g),
如果是要得到所有匹配项的捕获组的信息则使用str.matchAll(pattern/g)

  • search

str.search(reg)

参数: 一个正则表达式对象,如果reg不是正则表达式对象,则会利用new RegExp(reg) 隐式转换。
返回值: 如果匹配成功则返回正则表达式在字符串中首次匹配项的索引,否则返回-1。
const str = "hey JudE";
const re = /[A-Z]/g;
const re2 = /[.]/g;
// returns 4, which is the index of the first capital letter "J"
console.log(str.search(re));
// returns -1 cannot find '.' dot punctuation
console.log(str.search(re2)); 
  • replace
    str.replace(regexp|substr, newSubStr|function)
参数:
  - regexp (pattern): 一个正则表达式对象,其匹配的值,会被第二个参数返回的值替换。
  - substr (pattern): 字符串,如果匹配会被第二个参数返回的值替换,并且仅第一个匹配项被替换。
  - newSubstr(relacement): 用于替换掉第一个参数匹配部分的字符串,并其其可以内插一些特殊变量。
  - function (replacement): 其返回的新字符串用来替换掉第一个参数匹配的部分。
返回:
  部分或全部由匹配模式所取代的新字符串。

newSubstr 中可以插入的特殊变量

变量名 代表的的值
$$ 插入一个"$"
$& 插入匹配的子串
$` 插入当前匹配的子串左边的内容
$' 插入当前匹配的子串右边的内容
$n 如果第一个参数是正则表达式,则$n是第n个捕获组匹配到内容,如果不存在$n 则会转为字符串$n |
$ Name 为命名分组的名称,如果没有匹配或无此分组,则其值为空字符串, (?) 命名分组
/** 交换字符串中的两个单词 **/
const str = "John Smith";
const newstr = str.replace(/(?<name>\w+)\s(\w+)/, "$2 $$ $1 $3 $<name>");
console.log(newstr);  // Smith $ John $3 John

function 函数作为第二个参数

变量名 代表的的值
match 匹配的子串, 对应为上面的$&
p1, p2, ... 如果第一个参数是正则表达式, 则p1 代表第一个捕获组匹配的内容, 相当于$1
offset 匹配到的子字符串的首字符在原字符中的位置
string 被匹配的原字符串
group 命名捕获组匹配的对象

注意: 具体参数个数取决于replace方法的第一个参数是否是正则表达式以及捕获组的个数等

const str = "John Smith";
const newstr = str.replace(/(?<name>\w+)\s(\w+)/, (match, p1, p2, offset, string, group) => {
  console.log('match: ', match); // match:  John Smith
  console.log('p1: ', p1); // p1:  John
  console.log('p2: ', p2); // p2:  Smith
  console.log('offset: ', offset); // offset:  0
  console.log('string: ', string); // string:  John Smith
  console.log('name: ', group.name); // name:  John
  return `${p2} ${p1}`;
});
console.log(newstr);  // Smith John
  • replaceAll

str.replaceAll(regexp|substr, newSubStr|function)

参数: 其参数与replace方法一样,如果第一个参数使用正则表达式,则必须使用g修饰符,否则程序会抛出类型错误。
返回: 返回一个替换了所有匹配项的新字符串。
const res = 'aabbcc'.replaceAll('b', '.');
console.log(res); // aa..cc

const res = 'aabbcc'.replace(/b/g, '.');
console.log(res); // aa..cc

注意: 由上面的例子可以看出,使用relace方法第一个参数使用正则表达式的全局模式,可以替代replaceAll方法。

  • split

str.split([separator[, limit]])

参数: 
  - separator:指定每一个拆分点的字符串或匹配模式。
    如果separator不指定则返回包含被分隔字符串的数组,
    如果separator为空字符串,则返回包含被分隔字符串每一个字符形成的数组.
  - limit: 限定返回的数量
返回:返回以分隔符拆分的子字符串数组。
/**  使用不捕获组(?:)正则表达式分隔字符串 **/
const names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
const nameList = names.split(/\s*(?:;|$)\s*/);
// [ 'Harry Trump', 'Fred Barney', 'Helen Rigby', 'Bill Abel', 'Chris Hand', '' ]
console.log(nameList); 

/** 使用limit参数限定返回的数组项 **/
const limitedNameList = names.split(/\s*(?:;|$)\s*/, 5);
// [ 'Harry Trump', 'Fred Barney', 'Helen Rigby', 'Bill Abel', 'Chris Hand']
console.log(limitedNameList);

/** 使用捕获组正则表达式分隔字符串包含分隔符 **/
const nameList = names.split(/\s*(;|$)\s*/);
console.log(nameList);
// [ 'Harry Trump', ';', 'Fred Barney', ';', 'Helen Rigby', ';', 'Bill Abel', ';', 'Chris Hand', '', '' ]

标签:编程,匹配,log,正则表达式,javascript,console,str,字符串,const
From: https://www.cnblogs.com/xiaodi-js/p/16932760.html

相关文章

  • 1、引入Javascript的几种方式
    <scripttype="text/javascript">window.alert("hellojs");//alert函数会阻塞整个页面加载的作用,当我们把script放到最前面//当alert按......
  • C++数据结构和算法:位运算、字符串
    --------------------------------位运算---------------------------------Q1.用位运算交换两个值前提:要交换的两个值是独立内存voidSwap(int&a,int&b){a......
  • JavaScript笔记
    JavaScript合集学完HTML5+CSS3的小伙伴,学习JS时,要多敲多练多想多拓展刚开始入门JS的时候,我们不需要纠结那么多,有些需要先记住,后面会慢慢明白为什么是这样的JS基础部分......
  • R语言代做编程辅导和解答:Lab Activities - MAT 500
    Completethefollowingexercisesusingthecodediscussedduringcomputerlab.SaveyourworkinanRscriptaswellasaWorddocumentcontainingthenecessary......
  • 【转】C语言表驱动法编程实践
    来源:C语言表驱动法编程实践(精华帖,建议收藏并实践)(qq.com)数据压倒一切。如果选择了正确的数据结构并把一切组织的井井有条,正确的算法就不言自明。编程的核心是数据结......
  • python的几种字符串分割方法(partition)
    split最常用的方法re.splitsplitlines按行进行分割partition#使用split进行分割是,若分割符合不存在,会返回一个列表,含有一个元素'abc'.split('d')#['abc']#......
  • 字符串相加
    字符串相加一、题目描述给定两个字符串形式的非负数num1henum2,计算它们的和并以字符串的形式返回。不能使用任何的内建函数。示例1:输入:num1="11",num2="123"输......
  • 1758. 生成交替二进制字符串的最少操作数
    1758.生成交替二进制字符串的最少操作数给你一个仅由字符'0'和'1'组成的字符串s。一步操作中,你可以将任一'0'变成'1',或者将'1'变成'0'。交替字符串定义......
  • JAVA格式化数字字符串,如手机号,银行卡号的格式化
     格式化手机号码为335Stringmobile="13123456789";Stringregex="(\\d{3})(\\d{3})(\\d{5})";StringformatedMobile=mobile.replaceAll(regex,"$1$2$3")......
  • 1758. 生成交替二进制字符串的最少操作数 ---- 位运算、模拟
    给你一个仅由字符'0'和'1'组成的字符串s。一步操作中,你可以将任一'0'变成'1',或者将'1'变成'0'。交替字符串定义为:如果字符串中不存在相邻两个字符相等的情......