Assuming we have a comment textarea where the user can enter this code:
[quote="comment-1"]
How can I replace that code before the form submits with the actual html content from <div id="comment-1"> ?
You could try something like this:
http://jsfiddle.net/5sYFT/1/
var text = $('textarea').val();
text = text.replace(/\[quote="comment-(\d+)"\]/g, function(str,p1) { return $('#comment-' + p1).text(); });
$('textarea').val(text);
It should match agains any numbered quote in the format you gave.
You can use regular expressions:
text = text.replace(/\[quote="([a-z0-9-]+)"]/gi,
function(s, id) { return $('#' + id).text(); }
);
If I understand you correctly, you wish to replace something like '[quote="comment-1"]' with ''.
In JavaScript:
// Where textarea is the reference to the textarea, as returned by document.getElementById
var text = textarea.value;
text = text.replace(/\[quote\="(comment\-1)"\]/g, '<div id="$1">');
In jQuery:
// Where textarea is the reference to the textarea, as returned by $()
var text = textarea.val();
text = text.replace(/\[quote\="(comment\-1)"\]/, '<div id="$1">');
Hope this helps!
Related
In my project I have some html with comments surrounding text so I can find the text between particular comments and replace that text whilst leaving the comments so I can do it again.
I am having trouble getting the regex to work.
Here is an html line I am working on:
<td class="spaced" style="font-family: Garamond,Palatino,sans-serif;font-size: medium;padding-top: 10px;"><!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname--> <span class="spacer"></span></td>
Now, here is the javascript/jquery that I have at the moment:
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
currentTemplate = $("#gentextCodeArea").text(); //fetch the text
var tokenstring = "<!--" + thistoken + "-->"
var pattern = new RegExp(tokenstring + '\\w+' + tokenstring,'i');
currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").text(currentTemplate); //put the new text back
I think I'm pretty close, but I don't have the regex right yet.
The regex ought to replace the firstname with whatever is entered in the textbox for $thisval (method is attached to keyup procedure on textbox).
Using plain span tags instead of comments would make things easier, but either way, I would suggest not using regular expressions for this. There can be border cases that may lead to undesired results.
If you stick with comment tags, I would iterate over the child nodes and then make the replacement, like so:
$("#fname").on("input", function () {
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
var between = false;
$("#gentextCodeArea").contents().each(function () {
if (this.nodeType === 8 && this.nodeValue.trim() === thistoken) {
if (between) return false;
between = true;
} else if (between) {
this.nodeValue = thisval;
thisval = '';
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
<!--firstname-->Harrison<!--firstname-->
<!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div>
What went wrong in your code
By using text() you don't get the comment tags. To get those, you need to use html() instead
replace() does not mutate the variable given in the first argument, but returns the modified string. So you need to assign that back to currentTemplate
It would be better to use [^<]* instead of \w+ for matching the first name, as some first names have non-letters in them (hyphen, space, ...), and it may even be empty.
Here is the corrected version, but I insist that regular expressions are not the best solution for such a task:
$("#fname").on("input", function () {
var thisval = $(this).val(); //gets replacement text from a text box
var thistoken = "firstname";
currentTemplate = $("#gentextCodeArea").html(); //fetch the html
var tokenstring = "<!--" + thistoken + "-->"
var pattern = new RegExp(tokenstring + '[^<]*' + tokenstring,'i');
currentTemplate = currentTemplate.replace(pattern, tokenstring + thisval + tokenstring);
$("#gentextCodeArea").html(currentTemplate); //put the new text back
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
New first name: <input id="fname">
<div id="gentextCodeArea">
<!--firstname-->Harrison<!--firstname-->
<!--lastname-->Ford<!--lastname-->
<span class="spacer"></span></div>
here is a function which will generate an appropriate Regular expression:
function templatePattern(key) {
return new RegExp(`<!--${key}-->(.*?)<!--${key}-->`);
}
the (.*?) means "match as little as possible," so it will stop at the first instance of the closing tag.
Example:
'<!--firstname-->Harrison<!--firstname--> <!--lastname-->Ford<!--lastname-->'
.replace(templatePattern('firstname'), 'Bob')
.replace(templatePattern('lastname'), 'Johnson') // "Bob Johnson"
$(function(){
function onKeyUp(event)
{
if(event.which === 38) // if key press was the up key
{
$('.firstname_placeholder').text($(this).val());
}
}
$('#firstname_input').keyup(onKeyUp);
});
input[type=text]{width:200px}
<input id='firstname_input' type='text' placeholder='type in a name then press the up key'/>
<table>
<tr>
<td ><span class='firstname_placeholder'>Harrison</span> <span class='lastname_placeholder'>Ford</span> <span class="spacer"></span></td>
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I have function which gets the html generated in the iframe and replaces with custom tags.For eg.<b></b> tag is replaced with [b][/b]. likewise when i press tab key ,<span class="Apple-tab-span" style="white-space:pre"></span> is generated, how do i replace this with [tab][/tab] custom tag?.Please find the script which replaces bold tag, i tried replacing the whole span tag but it did not work.
Script:
function htmltoBBcode() {
var html = $("#textEditor").contents().find("body").html();
html = html.replace(/\</gi, '[');
html = html.replace(/\>/gi, ']');
$("#custom-tag").text(html);
}
Any help much appreciated.
Jsfiddle:
You can do it like this:
function htmltoBBcode() {
var html = $("#textEditor").contents().find("body").html();
html = html.replace(/\<span.*?\>/gi, '[tab]');
html = html.replace(/\<\/span\>/gi, '[/tab]');
html = html.replace(/\</gi, '[');
html = html.replace(/\>/gi, ']');
$("#custom-tag").text(html);
}
fiddle
Very easy!
$('p').click(function(){
var t = $(this).prop('outerHTML').replace(/</g, '[').replace(/>/g, ']');
$('#custom-tag').text(t);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click me!</p>
<div id="custom-tag"></div>
retrieving text from body tag will encode it as html, I thought you could save anywhere in a temporary textarea to decode it, than replace in the output, like this:
function decodeEntities(encodedString) {
var textArea = document.createElement('textarea');
textArea.innerHTML = encodedString;
return textArea.value;
}
To replace your span tag, replace your regex like this:
html.replace(/<span>(.+)<\/span>/, '[tab]$1[/tab]');
See updated fiddle
Hope it will help! :)
I have this html code
<div class="myDiv">
My link
<p>This is a paragraph</p>
<script>//This is a script</script>
</div>
And I this javascript:
$('.myDiv').children().each(
function() {
var strToStrip = $('.myDiv').html();
if ( this.tagName != 'A' ) {
// Strip tag element if tagName is not 'A'
// and replace < or > with < or >
strToStrip.replace(/(<([^>]+)>)(?!(a))/ig, "");
}
}
);
How can I strip all tags, except from the a element?
I only need the link and strip tags if it is not a link tag.
I can't find what wrong with this code and what regex can I use to do this.
Any help please?
Try this regex example:
var strToStrip = $('.myDiv').html();
var temp = strToStrip.replace(/<[^a\/][a-z]*>/g, "<");
var result = temp.replace(/<\/[^a][a-z]*>/g, ">");
alert(result);
My goal of this question is to figure out how twitter do his hashtag or usergroup by using # or #. Go here to see the final result
you can use replace method of string using regular expr
var html = $("#main").html();
var result = html.replace(/[\<\>\/]/g,'');
alert(result);
the example shown here
I need to style the total cost for user added in a textarea.
I have this fragment of code:
$("#student_teacher_profile_for_teaching_amount").keyup(function(e) {
var new_str, price, regex, str;
regex = /[0-9]+\.[0-9]{1,2}|[0-9]/;
str = $(this).val();
console.log(str);
price = str.match(regex);
if(price) {
if( $("#to_teach_ammount").length > 0 ) {
$("#to_teach_ammount").html(price[0]);
} else {
new_str = str.replace(regex, "<span id='to_teach_ammount'>" + price[0] + "</span>");
$(this).val(new_str);
}
$("#to_teach_total").val(price[0]); #this is and hiddent input filed
}
});
As a result of it I get:
some text before numbers <span id='to_teach_ammount'>2</span>
in my textarea.
How can I convert this into raw HTML?
This is not possible with a common <textarea> element, which only accepts plain text. You will have to use a (rich-text)-plugin, for example with jQuery. Have a look here: http://www.strangeplanet.fr/work/jquery-highlighttextarea/
The to_teach_total should not be a textarea. Instead it should be an element which expects html
Then use $(this).html(new_str) to set html
This html() method can also be passed a function which can take old html as parameter and return a new string to be set as new html
So if I call this function:
$("#item").text()
on this HTML code:
<div id="item">
<pre><span class="cm-tag"><html></span></pre><pre><span class="cm-tab"> </span>asdf</pre><pre><span class="cm-tag"></html></span></pre>
</div>
it returns:
'<html> asdf</html>'
and i want it to return:
'<html>
asdf
</html>'
basically i need a new line after each <pre> tag... how would i do this?
A possible solution, get the text of each pre and join them with new lines:
var text = $("#item pre").map(function(){
return $(this).text();
}).get().join('\n');
Here is the jsfiddle: http://jsfiddle.net/uGGFe/
Another option for you:
var clone = $("#item").clone(); //create a clone we can manipulate
clone.find('pre').after('\n'); //stick new lines in after <pre> tags
alert(clone.text()); //behold the alert glory
http://jsfiddle.net/SrV9c/1/
var text = '';
$("#item pre").map(function(i, el) {
return $(el).text().replace(/\s/g, '')
}).each(function(i, val) {
if (i == 0)
text += val.concat('\n\t');
else
text += val.concat('\n');
});
Working sample
because jQuery search match htmlElement use regular expression, when regular expression match content first delete "\r\n", so you see the content not have "\r\n"