I have following html<p class="get">This is some content.</p> what I would like to do is to make it like this:<p class="get">This is <span>some</span> content.</p>. To accomplish this I know I should: 1. get my certain text (done that...)
2. Wrap my text in span (done that also...)
3. replace my text with text that contains my span (haven't done it)
My problem is step 3 I just can't figure it out. So how can I replace my "old" text with new one?Thank you guys!!!
Fiddle here
My code looks like this:
$(document).ready(function(){
//get the whole text
var ptext = $(".get").text().split(" ");
var myText = ptext[2];
//alert(ptext[2])
//alert(myText);
if($('.get').text().contains(myText)){
//$('<span>'+myText+'</span>').appendTo($('.get'));
}
else{
alert('no text');
}
});
var word = "some",
regex = new RegExp("\\b" + word + "\\b", "g");
$(".get").html(function(i, html) {
return html.replace(regex, "<span>$&</span>");
});
DEMO: http://jsfiddle.net/V7Wnk/1/
$('.get').html(function (i, v) {
return v.replace('some', '<span>some</span>');
});
$('.get').html($(".get").html().replace("some","<span> some </span>"));
Related
Hiiii Everyone,
I have a Rich text Editor(using nicEditor).I want to make each words in richtextEditor clickable so that onclick of word will change background of particular word and again click removes bg which works like toggle.So that I triedin 1st step to make the words clickable I wanna wrap each words with span tag.
var myInstance1 = new nicEditor({
iconsPath: 'https://cdn.jsdelivr.net/nicedit/0.9r24/nicEditorIcons.gif'
}).panelInstance('differ_paragraph');
myInstance1.addEvent('blur', function() {
var text1 = this.instanceById('differ_paragraph').getContent();
var nicInstance1 = nicEditors.findEditor('differ_paragraph');
var words = nicInstance1.getContent().split(" ");
nicEditors.findEditor("differ_paragraph").setContent(' ');
$.each(words, function(i, v) {
nicEditors.findEditor("differ_paragraph").setContent($("<span>").text(v));
});
});
I tried like above but Its return object.What is the issue? Please anyone help me.Thanks in advance.
I'm trying to make a kind of simple search engine, where
the user enters a string and if it's equal to the text inside
an element, that portion of text must be highlighted some way.
This is the html:
<input type="text">
<input type="button" value="Change text"><br>
Click here to get more info!
this is the css:
.smallcaps{
color:red;
}
and this is the jquery function that makes the search and replace:
$("input[type='button']").click(function(){
var textValue = $("input[type=text]").val();
$("a").html(function(_, html) {
return html.replace(new RegExp(textValue,"ig"), '<span class="smallcaps">'+textValue+'</span>');
});
});
This is an example of how it looks like:
Everything works fine, until the search string is equals to the name of a node element, so for example if the search string is a, the html will be broken.
How can I avoid the replace of the html itself?. I just want to work over the text.
This is the codepen:
http://codepen.io/anon/pen/mefkb
Thanks in advance!
I assume that you want to only highlight the last search and not store the ones from before.
With this assumption, you can store the old value if it is the first call and use the stored value in the calls afterwards:
$("input[type='button']").click(function(){
// Escape the html of the input to be able to search for < or >
var textValue = $('<div/>').text($("input[type=text]").val()).html();
if(textValue === '') return;
$("a").html(function(_, html) {
var old = $(this).data('content');
if(!old) {
old = html;
$(this).data('content', old);
}
var replacer = function(match) {
return match.replace(new RegExp(textValue, "ig"), '<span class="smallcaps">'+textValue+'</span>');
};
if(/[<>]/.test(old)) {
return old.replace(/^[^<>]*</gi, replacer).replace(/>[^<>]*</gi, replacer).replace(/>[^<>]*$/gi, replacer);
}
return replacer(old);
});
});
Also i fixed two bugs I found when testing:
if you search for an empty string, everything is broken.
If you search for html characters like < or > nothing is found as in the text they are converted to < or >.
One thing is not solved, as it is not possible to easily implement it without destroying the subelement structure: It is not possible to search in different subelements, as you have to remove the tags, search then and insert the tags at the right position afterwards.
Working fiddle: http://codepen.io/anon/pen/KlxEB
Updated Demo
A workaround would be to restore <a> to original text, instead of complicating the regex.
Your problem is a form the <span> tag is getting replaced.
var init = $("a").text(); //save initial value
$("input[type='button']").click(function(){
$('a').text(init); //replace with initial value
var textValue = $("input[type=text]").val();
$("a").html(function(_, html) {
return html.replace(new RegExp(textValue,"ig"), '<span class="smallcaps">'+textValue+'</span>');
});
});
i don't know how to add this symbol '*' at front of every line of textarea. I have a hidden textarea which is #repmsg, and assume that in that box have 3 line. I want when user click #modquote, the confirm box will appear, and when user click OK, inside the textarea#modrepmsg will display
>line1
>line2
>line3
Here my jquery code
$( '#modquote')
.click(function() {
if (confirm('ausdhkajsdhskj?'))
{
var comment = $('#repmsg').val();
var regex = /<br\s*[\/]?>/gi;
var repmsg = comment.replace(regex, "")
var quote = '>' + repmsg;
$('textarea#modrepmsg').val(quote);
}
});
Thanks for helping.
Something like:
$('#modrepmsg').val(function() {
return $('#repmsg').val().split('\n').map(function(line) {
return '>'+line;
}).join('\n');
});
Demo: http://jsfiddle.net/cm7d6/
you could replace \r\n or what ever return / linebreak is in the text area and replace with \r>
then preceed the content with >
You want to use a regex that gets the beginning or a text line so ^ should be used
$( '#modquote')
.click(function() {
if (confirm('ausdhkajsdhskj?'))
{
var comment = $('#repmsg').val();
var repmsg = comment.replace("/^/g", ">")
$('textarea#modrepmsg').val(repmsg );
}
});
I have the following script which allows me to select text, and will then visually highlight it by wrapping the selected text in a span tag.
This normally works fine, but if there is a highlight tag separated from another highlight tag by only a space, it joins the two highlights together.
Javascript
var HVleftPanelContent = $("#highlight-view .top .content");
HVoutputUl = $("#highlight-view .contentBottom ul");
$("p").on("copy", highlight);
function highlight() {
var text = window.getSelection().toString();
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var textStr = selectedText.textContent;
if (textStr == "\n") {
clearSelection();
return false;
} else if (textStr[textStr.length - 1] == "\n") {
textStr = textStr.slice(0, -1);
var reg = new RegExp("\n", "g");
textStr = textStr.replace(reg, "\n<b data='
'></b>") + "\n";
} else if (textStr.indexOf("\n") >= 0) {
var reg = new RegExp("\n", "g");
textStr = textStr.replace(reg, "\n<b data='
'></b>");
}
var span = $("<span class='highlight'>" + textStr + "</span>");
selection.insertNode(span[0]);
if (selectedText.childNodes[1] != undefined) {
$(selectedText.childNodes[1]).remove();
}
var txt = HVleftPanelContent.html();
HVleftPanelContent.html(txt.replace(/<\/span>(?:\s)*<span class="highlight">/g, ''));
HVoutputUl.html("");
$("#highlight-view .top .content .highlight").each(function () {
$("#highlight-view .contentBottom ul").append("<li><span>" + $(this).html() + "</span></li>");
});
saveIt();
clearSelection();
}
Recap
If HTML looks like this:
This is a short paragraph
And I highlight "is", the markup changes to:
This <span>is</span> a short paragraph
And then I highlight either "this" or "a", the markup erroneously changes to:
This <span>isa</short> paragraph
Instead of how it should change:
This <span>is</span> <span>a</span> paragraph
Potential Problem
I assume the problem lays in this line:
HVleftPanelContent.html(txt.replace(/<\/span>(?:\s)*<span class="highlight">/g, ''));
Where the Regex statement is joining <span> tags that are next to each other, which it should so that if two span tags are directly next to each other, it becomes one span, but the Regex isn't limiting the joining to only when they're directly next to each other.
So, basically, how can I change the Regex to only join span tags if they're directly next to each other.
Fairly simple, replace:
HVleftPanelContent.html(txt.replace(/<\/span>(?:\s)*<span class="highlight">/g, ''));
With:
HVleftPanelContent.html(txt.replace(/<\/span><span class="highlight">/g, ''));
The problem was (?:\s)*, which means match any white space 0 or more times, which means that it would match even the spans that are separated with spaces.
How can I replace a specific text with HTML objects?
example:
var text = "some text to replace here.... text text text";
var element = $('<img src="image">').event().something...
function ReplaceWithObject(textSource, textToReplace, objectToReplace);
So I want to get this:
"some text to replace < img src...etc >.... text text text"
And I would like manipulate the object element without call again $() method.
UPDATE:
I solved.
thanx #kasdega, i made a new script based in your script, because in your script i can't modify the "element" after replace.
This is the script:
$(document).ready(function() {
var text = "some text to replace here.... text text text";
var element = $('<img />');
text = text.split('here');
$('.result').append(text[0],element,text[1]);
$(element).attr('src','http://bit.ly/mtUXZZ');
$(element).width(100);
});
I didnt know that append method accept multiples elements.
That is the idea, only need to automate for multiple replacements
thanx to all, and here the jsfiddle
do a split on the text you want to replace then use the array indexes 0 and 1...something like:
function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
var strings = textSource.split(textToReplace);
if(strings.length >= 2) {
return strings[0] + objectToReplace.outerHTML() + strings[1];
}
return "";
}
UPDATE: I found another SO post Get selected element's outer HTML that pointed me to a tiny jquery plugin that helps here.
I believe this jsfiddle has what you want. outerHTML is the tiny jquery plugin I included in the JSFiddle.
You can also use replace which will reduce some code: http://jsfiddle.net/kasdega/MxRma/1/
function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
return textSource.replace(textToReplace, objectToReplace.outerHTML());
}
function textToObj (text,obj,$src){
var className = "placeholder-"+text;
$src.html($src.html().replace(text,"<div class='"+className+"'></div>"));
$("."+className).replace(obj);
}
you can use $(selector).outerHtml to get the html string of an element
You can replace the html directly: http://jsfiddle.net/rkw79/qNFKF/
$(selector).html(function(i,o) {
return o.replace('old_html','new_html');
})