Reputation: 19
Here is my function:
function process() {
var content = document.getElementById('content').value;
content = content.replace(/(<tt>(.*?)<tt>)/g, '$2');
document.getElementById('content').value = content;
}
Here is my HTML:
<textarea id="content" cols="48" rows="8"></textarea><br />
<input type="button" value="Process" onclick="process()" />
Sample code:
<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
and if you were to run this code:
<tt>hel lo<tt>
Through the function, this will be your result:
hel lo
the result I would prefer would be:
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
then the result would be
d_j1_2
instead of what I would prefer which would be
d_j1 2
To summarize, I would like to replace a space with a underscore but only between my
<tt><tt>
tags. Help is always appreciated and thank you very much in advance. I will provide this link to my example as well: jsfiddle example
Upvotes: 1
Views: 2451
Reputation: 150040
The first way that came to mind is as follows:
content = content.replace(/(<tt>(.*?)<tt>)/g, function(m,p1,p2) {
return p2.replace(/ /g,"_");
});
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.
Demo: http://jsfiddle.net/WVUYX/42/
Upvotes: 1