admin 管理员组

文章数量: 1184232


2024年3月7日发(作者:evaluat)

js replace 函数参数

replace() 函数接受两个参数:

1. 要被替换的字符串或正则表达式。

2. 用来替换的字符串或一个返回替换字符串的函数。

语法:

e(regexpsubstr, newSubStrfunction)

实例:

1. 使用字符串替换

javascript

const str = 'hello, world!';

const result = e('world', 'javascript');

(result); "hello, javascript!"

2. 使用正则表达式替换

javascript

const str = 'javascript is cool!';

const result = e(/cool/, 'awesome');

(result); "javascript is awesome!"

3. 使用函数替换

javascript

const str = 'Today is 2022/02/01';

const result = e(/d{4}d{2}d{2}/, (match) => {

const [year, month, day] = ('/');

return `{day}-{month}-{year}`;

});

(result); "Today is 01-02-2022"

在这个例子中,我们使用一个正则表达式来匹配日期格式,并且传递了一个函数作为替换字符串的参数。当它匹配到日期格式时,它会执行这个函数来返回替换

字符串。


本文标签: 替换 函数 字符串 使用 返回