JavaScript 提供了两个函数来用另一个字符串替换一个字符串。今天的帖子将教我们两个用破折号('-')替换空格('')的功能。
目录
1.在JavaScript 中使用replaceAll()破折号替换空格
2.在JavaScript中使用replace()破折号替换空格
1.在JavaScript 中使用replaceAll()破折号替换空格
该replaceAll()
技术返回一个新字符串,其中模式的所有匹配都被替换替换。
模式通常是字符串或正则表达式,因此替换可能是字符串或每次匹配都必须调用的函数。
句法:
replaceAll(regexp, newSubstr)
replaceAll(regexp, replacerFunction)
replaceAll(substr, newSubstr)
replaceAll(substr, replacerFunction)
regexp
or 模式是带有全局标志的对象或文字。匹配被替换为newSubstr
或指定替换函数返回的值。
没有全局标志的 RegExpg
会引发 TypeError: replaceAll must be called with a regular expression
。substr
是一个应该替换为的字符串newSubstr
。
它被视为文字字符串,而不被解释为正则表达式。
newSubstr
or是将replace
指定的子字符串替换为指定的regexp
orsubstr
参数的字符串。允许使用几种特殊的替换模式。
replacerFunction
调用or函数来创建新的replacement
子字符串,用于将匹配项替换为指定的正则表达式或子字符串。
一个新字符串作为输出返回,模式的所有匹配都被替换
replaceAll
有关该功能的更多信息,请参见本文档
const p = 'Hello World! Welcome to my blog post.';
console.log(p.replaceAll(' ', '-'));
const regex = /\s/ig;
console.log(p.replaceAll(regex, '-'));
在上面的示例中,我们将空格替换为字符串,并将“-”作为新字符串应用于声明。如果要替换复杂的字符串,可以使用正则表达式。
它会自动找到适当的模式并将其替换为replaceAll
函数或替换字符串。
输出:
"Hello-World!-Welcome-to-my-blog-post."
"Hello-World!-Welcome-to-my-blog-post."
2.在JavaScript中使用replace()破折号替换空格
该replace()
技术返回一个新字符串,其中模式的所有匹配都被替换替换
模式通常是字符串或正则表达式,因此替换可能是字符串或每次匹配都必须调用的函数。
如果模式是字符串,它只会替换第一个匹配的匹配项。
句法
replace(regexp, newSubstr)
replace(regexp, replacerFunction)
replace(substr, newSubstr)
replace(substr, replacerFunction)
regexp
or 模式是带有全局标志的对象或文字。匹配被替换为newSubstr
或指定替换函数返回的值。
没有全局标志的 RegExpg
会引发 TypeError: replace must be called with a regular expression
。substr
是一个应该替换为的字符串newSubstr
。
它被视为文字字符串,而不被解释为正则表达式。
newSubstr
or是将replace
指定的子字符串替换为指定的regexp
orsubstr
参数的字符串。允许使用几种特殊的替换模式。
replacerFunction
调用or函数来创建新的replacement
子字符串,用于将匹配项替换为指定的正则表达式或子字符串。
一个新字符串作为输出返回,模式的所有匹配都被替换
replace
有关该功能的更多信息,请参见本文档
const p = 'Hello World! Welcome to my blog post.';
console.log(p.replace(' ', '-'));
const regex = /\s/ig;
console.log(p.replace(regex, '-'));
在上面的示例中,我们将空格替换为字符串,并将“-”作为新字符串应用于声明。如果要替换复杂的字符串,可以使用正则表达式。
它会自动找到适当的模式并将其替换为replace
函数或替换字符串。
输出
"Hello-World! Welcome to my blog post."
"Hello-World!-Welcome-to-my-blog-post."
replace
和之间的唯一区别replaceAll
是,如果搜索参数是字符串,则将replaceAll()
所有出现的搜索替换为替换值或函数。
相反,replace()
仅替换第一次出现