HOWTO · JavaScript

在 JavaScript 中用破折号替换空格

这篇文章介绍了如何使用 replaceAll() 和 replace() 方法在 JavaScript 中用破折号替换空格。

本页内容

JavaScript 提供了两个函数来用另一个字符串替换一个字符串。今天的帖子将教我们两个用破折号(’-’)替换空格(’’)的功能。

在 JavaScript 中使用 replaceAll() 用破折号替换空格

replaceAll() 技术返回一个新字符串,其中模式的所有匹配都被替换替换。

模式通常是字符串或正则表达式,因此替换可能是字符串或每次匹配都必须调用的函数。

语法:

replaceAll(regexp, newSubstr)
replaceAll(regexp, replacerFunction)

replaceAll(substr, newSubstr)
replaceAll(substr, replacerFunction)

regexp 或模式是带有全局标志的对象或文字。匹配被替换为 newSubstr 或指定替换函数返回的值。

没有全局标志 g 的 RegExp 会引发 TypeError:replaceAll must be called with a regular expression。substr 是应替换为 newSubstr 的字符串。

它被视为文字字符串,而不被解释为正则表达式。

newSubstr 或 replace 是用指定的 regexp 或 substr 参数替换指定子字符串的字符串。允许使用几种特殊的替换模式。

调用 replacerFunction 或 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."

在 JavaScript 中使用 replace() 用破折号替换空格

replace() 技术返回一个新字符串,其中模式的所有匹配都被替换替换。

模式通常是字符串或正则表达式,因此替换可能是字符串或每次匹配都必须调用的函数。

如果模式是字符串,它只会替换第一个匹配的匹配项。

语法:

replace(regexp, newSubstr)
replace(regexp, replacerFunction)

replace(substr, newSubstr)
replace(substr, replacerFunction)

regexp 或模式是带有全局标志的对象或文字。匹配被替换为 newSubstr 或指定替换函数返回的值。

没有全局标志 g 的 RegExp 会引发 TypeError:replace must be called with a regular expression。substr 是应替换为 newSubstr 的字符串。

它被视为文字字符串,而不被解释为正则表达式。

newSubstr 或 replace 是用指定的 regexp 或 substr 参数替换指定子字符串的字符串。允许使用几种特殊的替换模式。

调用 replacerFunction 或 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() 仅替换第一次出现。