JavaScript用空格替换下划线 [英] Javascript replace underscore with space

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

问题描述

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

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或jquery我想选择一个带有其名称的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 or jquery i want to select a certain div with the name in it and replace the underscore with a space

示例

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

在div.name中,我要说的是我的名字,而不是My_name

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

我当前正在为项目使用jQuery和jQuery UI

I'm currently using jQuery, and jQuery UI for my project

推荐答案

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

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

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

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

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, ' '));
});

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

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