在 JavaScript 中用破折号替换空格

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

目录

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

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


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

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

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

句法:

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

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

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

没有全局标志的 RegExpg会引发 TypeError: replaceAll must be called with a regular expressionsubstr是一个应该替换为的字符串newSubstr

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

newSubstror是将replace指定的子字符串替换为指定的regexporsubstr参数的字符串。允许使用几种特殊的替换模式。

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)

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

没有全局标志的 RegExpg会引发 TypeError: replace must be called with a regular expressionsubstr是一个应该替换为的字符串newSubstr

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

newSubstror是将replace指定的子字符串替换为指定的regexporsubstr参数的字符串。允许使用几种特殊的替换模式。

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()仅替换第一次出现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值