内容替换功能:用下划线替换空格 [英] content replace function: replacing a space with an underscore

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

问题描述

这是我的功能:

function process() {
var content = document.getElementById('content').value;
content = content.replace(/(<tt>(.*?)<tt>)/g, '$2');
document.getElementById('content').value = content;
}

这是我的 HTML:

<textarea id="content" cols="48" rows="8"></textarea><br />
<input type="button" value="Process" onclick="process()" />

示例代码:

<tt>hello<tt>

我的问题的目的是找出是否可以用下划线"替换空格"例如,目前如果您要从上面获取我的示例代码并通过我的函数运行它,您将省略以下代码:

The purpose of my question is to find out if I can replace a "space" with an "underscore" For instance, currently if you were to take my sample code from above and run it through my function you will omit this following code:

hello

如果您要运行此代码:

<tt>hel lo<tt>

通过函数,这将是你的结果:

Through the function, this will be your result:

hel lo

我更喜欢的结果是:

hel_lo

用下划线代替空格.我确实意识到我可以插入这样的内容:

Which replaces the space with a underscore. I do realize I could insert something like this:

content = content.replace(/()/g, '_');

进入我的函数,但是如果要这样做然后运行下面的代码:

Into my function, But if were to do that and then run this code below:

<tt>d j<tt>1 2

那么结果就是

d_j1_2

而不是我更喜欢的

d_j1 2

总而言之,我想用下划线替换空格,但仅限于我的

To summarize, I would like to replace a space with a underscore but only between my

<tt><tt>

标签.帮助总是受到赞赏,并在此先非常感谢您.我还将提供此示例的链接:jsfiddle 示例

tags. Help is always appreciated and thank you very much in advance. I will provide this link to my example as well: jsfiddle example

推荐答案

第一个想到的方法如下:

The first way that came to mind is as follows:

content = content.replace(/(<tt>(.*?)<tt>)/g, function(m,p1,p2) {
             return p2.replace(/ /g,"_");
          });

.replace()方法 接受第二个参数中的回调,以便您可以对匹配项进行自定义处理.回调接收匹配和子匹配作为参数,无论您的回调返回什么,都将用作替换文本,因此您可以仅替换第二个子匹配上的空格.

The .replace() method accepts a callback in the second parameter so that you can do custom processing on the match(es). The callback receives the match and submatches as parameters, and whatever your callback returns will be used as the replacement text, so you can replace the spaces on just the second submatch.

演示:http://jsfiddle.net/WVUYX/42/

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

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