Remove dashes and wrap with <li> with javascript/jquery - javascript

I have a "list" that looks like this:
-1+ years of experience in End User Support<br>
-Experience re-imaging laptops<br>
-Great customer service experience
And I want to turn it into an unordered list.
I wrapped the block in a <ul></ul> and then I used this code to remove the <br> and wrap with <li></li>:
$('.entry-content ul').each(function() {
var $this = $(this);
$this.html($this.html().replace(/[^\r\n]+/g, '<li>$&</li>'));
});
This outputs an unordered list like this:
-1+ years of experience in End User Support
-Experience re-imaging laptops
-Great customer service experience
But I don't know how to remove the dashes, too. I tried doing a second replace function after the first one, like this: $this.html($this.html().replace((/-/g, ' ')); , but that didn't work.
How can I achieve this?

var str = str = "-Experience re-imaging laptops";
console.log(str.replace(/^-/, ''));

Your posted code doesn't actually remove the <br> tags, you just don't see them in the results. I'd replace those, and any "-" after a newline or at the beginning of the text, with newlines, then replace as above.
$('.entry-content ul').each(function() {
var $this = $(this);
$this.html(
$this
.html()
.trim()
.replace(/^-|[\r\n]+-|<br>/g, "\n")
.replace(/[^\r\n]+/g, '<li>$&</li>')
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class=entry-content>
<ul>
-1+ years of experience in End User Support<br>
-Experience re-imaging laptops<br>
-Great customer service experience
</ul>
</div>

Related

Search all words in the input field, then replace all matching words in the div tag

$('#srctxt div').each(function() {
var dari = $('#box').val();
var text = $(this).text();
$(this).html(text.replace(dari, '<b>'+dari+'</b>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form method="POST">
<input type="text" id="box" value="love"> // working
<input type="text" id="box" value="love girl"> // not working
<div id="srctxt">
<div>i love you</div>
<div>love girl</div>
<div>not love</div>
<div>love love love</div>
</div>
</form>
I'm developing a search site by bolding every matching word of the input word with search results.
If only a word is entered, such as the word love, then this script works quite well. But if using two or more words, then this script does not work properly.
for example the word love girl, then the bold on the results for only one line. but it all contains the word love, so this is a problem for me.
sorry if my English is a bit hard to understand. however, I am asking for suggestions of this jQuery code fix. Thank you...
You can easily do this using regex
Here are the steps:
Step-1. Split the input value to make an array of input words.
Step-2. Iterate over all the div for which you want to execute search/replace condition
Step-3. For each word in input array create a searchregexp and replace if found
if ($('#box').val().length !== 0) {
var dari = $('#box').val().split(' ');
$('#srctxt div').each(function() {
dari.map(item => {
var regex = new RegExp('(' + item + ')(?!>|b>)', 'gi');
$(this).html($(this).html().replace(regex, "<b>$1</b>"));
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="box" value="love girl b">
<div id="srctxt">
<div>i love you</div>
<div>love girl</div>
<div>not love</div>
<div>love love love</div>
</div>
Also I removed the duplicate input field having same id as it is invalid html.
I think you will have to loop through your text in the search field. Assuming no special characters (-,{,}, > etc) are entered you can do following
$('#srctxt div').each(function() {
var dari = $('#box').val().split(" ");
var text = $(this).text();
dar.map((val, index) => {
$(this).html(text.replace(val, '<b>'+val+'</b>'));
});
});
Let me know if this helps.
maybe you have to split your search query, like:
'love girl'.split(' '); // ---> ['love','girl'];
and do a forEach on the resulting array and behave each one like your dari variable.
note that even if your word is one word, (like "love"), the result of split would still be an array. so you do not need to separate your logic into two branches.

Insert span in a dom element without overwrite child nodes?

I have an HTML article with some annotations that I retrieve with SPARQL queries. These annotations refer to some text in the document, and I have to highlight this text (wrapping it in a span).
I had already asked how to wrap text in a span, but now I have a more specific problem that I do not know how to solve.
The code I wrote was:
var currentText = $("#"+v[4]["element"]+"").text();
var newText = currentText.substring(0, v[5]["start"]) + "<span class=' annotation' >" + currentText.substring(v[5]["start"], v[6]["end"]) + "</span>" + currentText.substring(v[6]["end"], currentText.length);
$("#"+v[4]["element"]+"").html(newText);
Where:
v[4]["element"] is the id of the parent element of the annotation
v[5]["start"] is the position of the first character of the annotation
v[6]["end"] is the position of the last character of the annoation
Note that start and end don't consider html tags.
In fact my mistake consists in extracting data from the node with the text() method (to be able to go back to the correct position of the annotation) and put back with the html() method; but in this manner if parent node has children nodes, they will be lost and overwritten by simple text.
Example:
having an annotation on '2003'
<p class="metadata-entry" id="k673f4141ea127b">
<span class="generated" id="bcf5791f3bcca26">Publication date (<span class="data" id="caa7b9266191929">collection</span>): </span>
2003
</p>
It becomes:
<p class="metadata-entry" id="k673f4141ea127b">
Publication date (collection):
<span class="annotation">2003</span>
</p>
I think I should work with nodes instead of simply extract and rewrite the content, but I don't know how to identify the exact point where to insert the annotation without considering html tags and without eliminating child elements.
I read something about the jQuery .contents() method, but I didn't figure out how to use it in my code.
Can anyone help me with this issue? Thank you
EDIT: Added php code to extract body of the page.
function get_doc_body(){
if (isset ($_GET ["doc_url"])) {
$doc_url = $_GET ["doc_url"];
$doc_name = $_GET ["doc_name"];
$doc = new DOMDocument;
$mock_doc = new DOMDocument;
$doc->loadHTML(file_get_contents($doc_url.'/'.$doc_name));
$doc_body = $doc->getElementsByTagName('body')->item(0);
foreach ($doc_body->childNodes as $child){
$mock_doc->appendChild($mock_doc->importNode($child, true));
}
$doc_html = $mock_doc->saveHTML();
$doc_html = str_replace ('src="images','src="'.$doc_url.'/images',$doc_html);
echo($doc_html);
}
}
Instead of doing all these, you can either use $(el).append() or $(el).prepend() for inserting the <span> tag!
$("#k673f4141ea127b").append('<span class="annotation">2003</span>');
Or, If I understand correctly, you wanna wrap the final 2003 with a span.annotation right? If that's the case, you can do:
$("#k673f4141ea127b").contents().eq(1).wrap('<span class="annotation" />');
Fiddle:
$(document).ready(function() {
$("#k673f4141ea127b").contents().eq(1).wrap('<span class="annotation" />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="metadata-entry" id="k673f4141ea127b">
<span class="generated" id="bcf5791f3bcca26">Publication date (<span class="data" id="caa7b9266191929">collection</span>): </span>
2003
</p>
At the end my solution is in this Fiddle.
Generalizing:
var element = document.getElementById(id);
var totalText = element.textContent;
var toFindText = totalText.substring(start,end);
var toReplaceText = "<span class='annotation'>"+toFindText+"</span>";
element.innerHTML = element.innerHTML.replace(toFindText, toReplaceText);
Hope it could help someone else.
Note: This don't check if two or more annotations refers to the same node, I'm working on it right now.

Set a form value as that of a UL

I am using a jQuery plugin called 'tagit'.
I know you can't post a UL, but how can I get around that?
Lets say that I have:
<ul name="addtags" id="addtags" class="addtags" placeholder="Tags">
<li>Add your tags here</li>
</ul>
<input type="hidden" name="addtagsReal" />
When the form is submitted, I do validation with javascript. So I was thinking that, in my validation, I could simply set the hidden 'addtagsReal' input to that of the ul.
How can I do this with jQuery?
Thanks!
You essentially need a way to "serialize" the list, an older jquery plugin to do this is here:
jQuery serialize list
You can do something like this:
var separator = ",";
var str = $('#addtags').children('li').map(function(i,el){
return($(el).text());
}).get().join(separator);
$('input[name="addtagsReal"]').val(str);
And then you send your LIs separated by ´separator´, and explode them with PHP.
You can make comma separated 'data' strings with simple concatenation and some jQuery tomfoolery. There are certainly better ways to do it.
$(document).ready(function(){
var sampleTags = ['c++', 'java', 'php'],
eventTags = $('#eventTags');
eventTags.tagit({
availableTags: sampleTags,
afterTagAdded: function(evt, ui) {
updateTagInput();
},
afterTagRemoved: function(evt, ui) {
updateTagInput();
}
});
});
function updateTagInput() {
var $hidden = $('input[name=addtagsReal]'),
values = "";
$('#eventTags').find('.tagit-label').each(function(i, item){
values += $(item).text() + ', ';
});
// update the input and trim the final ', '
$hidden.val(values.substr(0, values.length - 2 ));
}
edit: oops! Deleted the plunk, thought I was deleting a version of it! Sorry, not going to recreate it but it used the html from the Events portion of this page http://aehlke.github.io/tag-it/examples.html

jquery text() not comparing to string

I am using javascript to hide some list Items based on the user role.
I am getting the role from a list item's text(). When I am comparing the $("#activeUser").text() value against a string, it is not working.
HTML Block that I am using in my javascript to get the text() value of a list item.
<ul class="pull-right breadcrumb">
<li>Home <span class="divider">/</span> </li>
<li id="activeUser" class="active"> <?php echo ucfirst($_SESSION['sewafs_user_role']); ?> </li>
</ul>
Javascript
$(document).ready(function () {
var testRole = $("#activeUser").text();
//This block of code works
role = 'Guest';
if (role == 'Guest') {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
//This doesn't work why?
if (testRole == 'Guest') {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
});
But if I see the value of the var testRole using alert it prints Guest.
I tried converting the testRole value into string using testRole.toString() / string(testRole) method, but nothing helped.
Please let me know, where I am going wrong. Thanks.
The problem seems to be extra white-spaces in the value that you receive from $("#activeUser").text()
Solution:
You must trim the value and then use it for comparison as:
var testRole = $("#activeUser").text().trim();
OR
var testRole = $.trim($("#activeUser").text());
OR
var testRole = $("#activeUser").text();
testRole = $.trim(testRole);
Any of the above will work.
More info on jQuery trim at this link.
Whitespace test:
If you want to test if you are getting extra white spaces, then try below javascript code:
alert("-" + $("#activeUser").text() + "-");
If you get "" then you dont have whitespaces in your received value.
But if you get spaces after < or before >, then these are white spaces, that are spoiling your party.
Try trimming the string, with $.trim($("#activeUser").text());
There seem to be whitespaces in your element.
You need to trim white spaces at start and end of the string:
var testRole = $("#activeUser").text().replace(/^\s+|\s+$/g,'');
You can see why here: http://jsfiddle.net/AfUZR/1/
Demo
$(document).ready(function () {
var testRole = $("#activeUser").text().trim();
//This doesn't work why?
if (testRole == "Guest") {
alert("Inside if");
$("#request_history_li").hide();
$("#assign_role_li").hide();
$("#volunteer_li").hide();
$("#profile_li").show();
$("#change_password_li").show();
}
});
Man, first what do you must do it, it's write correct selector.
$("#request_history_li").hide();
$("#assign_role_li").hide();
you can write
$("#request_history_li, #assign_role_li").hide();
or you can add the same classes of these Elements, that is correct
<ul>
<li class="same_class 1"></li>
<li class="same_class 2"></li>
</ul>
and
$(".same_class").hide();
ok? next:
As concerns your problem, js loaded earlier than you determine the role of, use
$(document).ready(function(){
......
});

javascript to replace all instances of a text within [] with hyperlinks

Am now facing an other challenge. Some parts of my html code has the following lines:
<div class="action-body flooded"><p>(In <span class="error">[82681]</span>) refs AGLBD-16096<br/></div>
I have to get the number with-in the [] and then replace it with a hyperlink. I have tried using document.getElementsByClassName('error') but its not working. how can I make it work? and i would also need to iterate in a loop to replace all such numbers if there are more than one in []. e.g: [123] [234] [345]...
This is all what I have written till now with pimvdb's help:
<script type="text/javascript">
var bodyText = document.getElementById('body').innerHTML;
var pattern = /\[.*?\]/g;
var replaceText = "Pradeep";
document.getElementById('body').innerHTML = bodyText.replace(pattern, replaceText);
</script>
This JSFiddle does what you need: http://jsfiddle.net/TNyms/
When you replace getElementById('body') with document.body, the code works for me.
var body = document.body;
var link = "Pradeep";
body.innerHTML = body.innerHTML.replace(/\[.*?\]/g, link);
That replaces all IDs in this with links:
<div class="action-body flooded">
<p>(In
<span class="error">[82681]</span>) refs
AGLBD-16096
<br/>
</div>
<div>[123][abcd]</div>
<div>[456]</div>
<div>[789]</div>
Outputs:
(In Pradeep) refs AGLBD-16096
PradeepPradeep
Pradeep
Pradeep
Try it with this fiddle.
Your question appears to be related to what is asked in the below link. You may refer this
Replace number in a string using regex or something else

Categories

Resources