Javascript Javascript用空格替换下划线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11810569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript replace underscore with space
提问by PhazingAzrael
I have an array with objects inside of it, a few of the objects contain an underscore in the string
我有一个包含对象的数组,其中一些对象在字符串中包含下划线
Example
例子
{"name": "My_name"}
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
但我在多个地方调用 name 函数,一个这样的地方是在需要下划线的图像标签中,使用 javascript 或 jquery 我想选择其中包含名称的某个 div 并用空格替换下划线
Example
例子
<div>
<div class="name">
My_name
</div>
<img src="My_name.jpg"/>
</div>
In the div.name I want it to say My name instead of My_name
在 div.name 我希望它说 My name 而不是 My_name
I'm currently using jQuery, and jQuery UI for my project
我目前正在为我的项目使用 jQuery 和 jQuery UI
回答by Ry-
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
:
因此,只需在放入内容之前执行此操作。如果您需要在之后执行替换,请循环使用each
:
$('.name').each(function() {
var $this = $(this);
$this.text($this.text().replace(/_/g, ' '));
});