如何用空格替换下划线? [英] How to replace underscores with spaces?

查看:74
本文介绍了如何用空格替换下划线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其中包含对象,其中一些对象在字符串中包含下划线.

I have an array with objects inside of it, a few of the objects contain an underscore in the string.

示例:

{"name": "My_name"}

但是我在多个地方调用了name函数,其中一个地方是在图像标签中必须使用下划线的地方,使用JavaScript,我想选择一个带有其名称的div并将下划线替换为空格.

But I'm calling the name function in multiple places, one such place is in an image tag where the underscore is necessary, using JavaScript I want to select a certain div with the name in it and replace the underscore with space.

示例:

<div>
 <div class="name">
  My_name
 </div>
 <img src="My_name.jpg"/>
</div>

div.name 中,我要说的是 My name ,而不是 My_name .

In the div.name I want it to say My name instead of My_name.

推荐答案

您可以将字符串中的所有下划线替换为如下空格:

You can replace all underscores in a string with a space like so:

str.replace(/_/g, ' ');

因此,只需在放入内容之前执行此操作.如果之后需要执行替换,请使用每个:

So just do that before the content is put in. If you need to perform the replacement afterwards, loop using each:

$('.name').each(function() {
    var $this = $(this);

    $this.text($this.text().replace(/_/g, ' '));
});

这篇关于如何用空格替换下划线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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