Trying to .replace() Without Success - javascript

I have some lines of HTML code that are like this:
<li>Testing jQuery [First Bracket]</li>
<li>Loving jQuery [Second one]</li>
I'm trying to replace what's inside the bracket with nothing onLoad, like this:
var item = $(".lstItem").text();
var match = item.match(/\[(.*?)\]/);
item = item.replace(match[0], "");
But nothing changes. What's wrong and how to correct this?
After using jimbojw's suggestion I'm getting a Uncaught ReferenceError: text is not defined at this particular line:
oldtext = $item.text,

item is a variable containing a string, not a pointer to the literal text. If you want to change the text, you have to set it again, vis a vis $(".listItem").text(item)
edit - predicting next problem
The next problem you're going to have is that all the text gets set to the same thing. So what you really want to do is probably something like this:
$(".lstItem")
.each(function(index, item) {
var
$item = $(item),
oldtext = $item.text(),
match = oldtext.match(/\[(.*?)\]/),
newtext = oldtext.replace(match[0], '');
$item.text(newtext);
});

this will do the job for you:
you are splitting your code in too much lines, also your need to run replace for each individual element separately.
$(".lstItem").each(function() {
$(this).html(
$(this).html().replace(/\[(.*)\]/, "")
);
});
see your example in jsFiddle: http://jsfiddle.net/eKn3Q/7/

Along with jimbojw's answer $(".lstItem").text() will retrieve all the text inside of your <a/> elements. One way to handle this would be to pass a function(i,t){} into the .text() method.
$(".lstItem").text(function(i, text){
var match = text.match(/\[(.*?)\]/);
return text.replace(match[0], "");
});
Simple example on jsfiddle

also your regex could be simpler.
var item = $(".lstItem").text();
var match = /\[(.*?)\]/;
$(".listItem").text(item.replace(match,""));

Related

How to remove element from HTML string?

This doesn't seem to be working, I get an Uncaught Type error on the .remove() line:
JS:
var str = $("a").html();
var $html = $.parseHTML(str);
$("i",$html).remove();
$("div").html($html);
HTML:
Hello <i>Bob</i>
<div></div>
How to get this to work?
You can remove the HTML tags by just using the .text() function.
var str = $("a").text();
$("a").text(str);
Which will result in:
Hello Bob
Example: http://jsfiddle.net/3s1c55w2/
How it works:
The $("a").text(); will retrieve only the text of the element, so in your case it will return Hello Bob.
Once you retrieve Hello Bob, simply set the a tags text value using .text(str) again, where the str is the value with no html tags.
You can clone a, change html code of clone and put clone inside div.
Fiddle.
$(document).ready(function()
{
var clone = $("a").clone();
clone.find("i").remove();
$("div").html(clone);
});
Maybe he's trying to remove i tags from every anchor.
http://jsfiddle.net/1fytum86/
$("a").each(function(index) {
var str = $(this).text();
$(this).html(str);
});
Anyway, it's possible that he was getting a type error because parseHTML() parses a string into an array of DOM nodes. Best of luck!
If you are trying to remove the italics and leave the text:
$("a").html($("a").html().replace(/<\/?i>/g, ""));
Otherwise, the other answers using either remove or detach would be appropriate.

jQuery how to insert <br/> tag after every Semicolon

I am dumping some CSS into a div and I am looking to format it so it is more legible. Basically what I want to do is insert a break tag after every semicolon. I have searched around for a while but can't seem to find something that quite fits what I am trying to do.
I have something like this...
HTML
<div class='test'>
color:red;background-color:black;
</div>​
jQuery
var test = $('.test').text();
var result = test.match(/;/g);
alert(result);​
And I have tried..
var test = $('.test').text();
var result = test.match(/;/g);
result.each(function(){
$('<br/>').insertAfter(';');
});
alert(result);​
Also I have started a fiddle here.. Which basically just returns the matched character...
http://jsfiddle.net/krishollenbeck/zW3mj/9/
That is the only part I have been able to get to work so far.
I feel like I am sort of heading down the right path with this but I know it isn't right because it errors out. I am thinking there is a way to insert a break tag after each matched element, but I am not really sure how to get there. Any help is much appreciated. Thanks...
try it like this
var test = $('.test').text();
var result = test.replace(/\;/g,';<br/>');
$('.test').html(result);​
http://jsfiddle.net/Sg5BB/
You can use a normal javascript .replace() method this way:
​$(document)​.ready(function(){
$(".test").html($(".test").html().replace(/;/g, ";<br />"));
});​
Fiddle: http://jsfiddle.net/SPBTp/4/
Use This CODE
var test = $('.test').text();
var result = test.split(';').join(';<br />')
http://jsfiddle.net/FmBpF/
You can't use jQuery selectors on text, it only works on elements.
Get the text, just replace each ; with ;<br/>, and put it back.
$('.test').html($('.test').text().replace(/;/g, ';<br/>'));
Try something like this :
var test = $('.test').text();
var result = test.replace(/;/g,";");
$('.test').html(result);
​
That should work if you stick it into your jfiddle.

comparing variable in javascript

I am in a predicament. I have been trying to compare two variables in javascript and then assign a class to parent element if matched. But i am having no success in this. I have searched through all possible codes and tried them but not able to get it working. The code i have written so far is as below:
$('div#encased a').click(function(){
$('ul#filter .current').removeClass('current');
var class_name = ($(this).parent().attr('class').replace('-',' '));
var className = class_name.toString();
alert(className);
$('ul#filter li').each(function(){
/*1st version
var filterValue = $(this).text().toLowerCase();
var filterValstr = filterValue.toString();
alert(filterValstr);
if(filterValstr==className)
{
alert("match!")
$(this).parent().addClass('current');
}*/
/*2nd version*/
if($(this).text().toLowerCase() == class_name)
{
$(this).parent().addClass('current');
}
/*this works which according to me means it is not entering the if clause
else{
$(this).parent().fadeOut('slow').addClass('hidden');
}*/
});
});
As per my knowledge the value is not going inside the if command at all as i tried using else function and that works. I am sure theres some silly error i am doing. I have tried 2 methods here and i have commented one but presented both of them here to know if any of them should be correct.
Basically on click of an image in my div#encased element the class name of the image is taken and then compared with the text in the filter menu above. If it matches the matched filter text should be assigned the class of current. Hope you are getting what i am trying to explain. Please help. thanks
Your code isn't clear, and kind of a spaghetti one, but maybe your problem is with white spaces, try trim them
var filterValue = $.trim($(this).text().toLowerCase());
And you should know that string.toString() return the string...
Example:
var str = "bla bla bla";
alert(str.toString === str); // true!

getting text value , regex or DOM method?

I have the following block
<span id="title"><select id="optionType"><option>choose option</option><option> hello</option><option>how are you</option></select></span>
I want to remove the first option and need to get the all other options in new line, only the option text with out any tags . Is regular expression is the best one to use, or is thire any other better method to retrieve text in new line ? I tried the following but it can fail somtimes
Description= $('title').innerHTML;
var tmp = Description;
tmp = tmp.replace("--Choose an option--</option>",""); // remove first option
tmp = tmp.replace(/<\/option><option>/g, "<\/option>\n<\/option>");
tmp = tmp.replace(/(<([^>]+)>)/g,"");
tmp = tmp.replace(/\n/g, "\n");
tmp = tmp.replace(/^[\s]*/gm, '');
return tmp;
Try with jQuery if possible instead of regex.
It would be something like
$("#optionType>option:first").remove() //to delete first option
$("#optionType>option") //list of other options
(<option[^>]*?>([^<]+)<\/option>)
Have you considered just removing the option directly rather than fiddling with the HTML code?
Particularly easy, since you're using JQuery already:
$("#title option[value='--Choose an option--']").remove();
See also: Removing an item from a select box

find and replace strings in jquery

$('img').click(function(){
var add_to_list = $(this);
// database query for element
});
Currently add_to_list is getting the value 'images/image.jpg'. I want to replace the 'image/' to nothing so I only get the name of the picture (with or without the extension). How can I do this? I couldn't find anything. Also please provide me with further reading on string manipulation please.
Have you tried javascript replace function ?
You should modify your code to something like this:
$('img').click(function(){
var add_to_list = $(this).attr('src').replace('images/', '');
// database query for element
});
use
add_to_list.substring(7);
This will get you the string after the 7th character. If there might be longer paths, you can split() into an array and get the last part of the path using pop().
add_to_list.split("/").pop();
substring
split
pop
This tutorial explains many of the string manipulation methods seen in the answers here.
$('img').click(function(){
var add_to_list = $(this).attr('src').replace('image/', '');
// database query for element
});
var pieces = add_to_list.split('/');
var filename = pieces[pieces.length-1];

Categories