javascript - 用空格替换破折号(连字符) [英] javascript - replace dash (hyphen) with a space

查看:101
本文介绍了javascript - 用空格替换破折号(连字符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找这个,虽然我发现了许多将空格更改为破折号(连字符)的回应,但我没有找到任何相反的回应.

I have been looking for this for a while, and while I have found many responses for changing a space into a dash (hyphen), I haven't found any that go the other direction.

最初我有:

var str = "This-is-a-news-item-";

我尝试将其替换为:

str.replace("-", ' ');

并简单地显示结果:

alert(str);

现在,它什么也没做,所以我不知道该去哪里.我尝试反转一些现有的用破折号替换空格的方法,但也不起作用.

Right now, it doesn't do anything, so I'm not sure where to turn. I tried reversing some of the existing ones that replace the space with the dash, and that doesn't work either.

感谢您的帮助.

推荐答案

这修复了它:

let str = "This-is-a-news-item-";
str = str.replace(/-/g, ' ');
alert(str);

您的代码有两个问题:

  1. 首先,String.replace() 不会改变字符串本身,它返回一个改变的字符串.
  2. 第二,如果你将一个字符串传递给替换函数,它只会替换它遇到的第一个实例.这就是为什么我通过 正则表达式g 标志,用于全局",以便替换所有实例.
  1. First, String.replace() doesn’t change the string itself, it returns a changed string.
  2. Second, if you pass a string to the replace function, it will only replace the first instance it encounters. That’s why I passed a regular expression with the g flag, for 'global', so that all instances will be replaced.

这篇关于javascript - 用空格替换破折号(连字符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆