How to compare a string, may be already in variable, with element taken from DOM?
with element like this
"Something here"
when i call this element with .text() method, i dont just get "Something here", but more like
"
Something
here
"
This is not a literal example, i mean my value is returned with additional whitespaces, and therefore i'm not able to compare it with anything, even if i copy whitespaced string from console.
EDIT
Pretty much all answers tell me to use $.trim, i tried it before and it doesnt work, doesnt remove all the whitespaces, still cant compare even with copy/paste from console.log
Trim and Compare:
if("string_to_compare" == $.trim(element.text())) {
//some code
}
You can use trim() to remove the trailing and leading spaces then compare them..
$.trim(x.text()) == 'abc'
$.trim() is used instead of String.trim() because of IE support
You can use $.trim to remove the spaces around the text you have.
$.trim($("selector").text())
The $.trim() function removes all newlines, spaces (including
non-breaking spaces), and tabs from the beginning and end of the
supplied string. If these whitespace characters occur in the middle of
the string, they are preserved, jQuery Doc.
If you do not want a dependency on JQuery, you should instead use a regular expression:
"Some String" == element.innerHTML.replace(/^\s+|\s+$/g, '');
can you specify the version of jquery you're using (+ post your code maybe) ? I've checked a couple of answers and made my own check and they all seem to work just fine.
Related
I am attempting to use the replace() function on a large amount of text, to filter out "[","{","(", and many other special characters. I initially attempted to just say:
replace(/"{"/g," ")
But this did not work, I tried a series of variations like this, using:
"/{/"g
or
"/{/g"
Yet, none of them worked. I have also tried attaching the first replace parameter to a variable as they do in the Mozilla tutorial.
var replacingStuff = /{/g;
str.replace(replacingStuff," ");
Does anyone have any ideas on how to fix this problem?
Use /[/[]/g as the regex to get rid of [
Basically, if you want to get rid of a certain character, it needs to be in brackets. For example, if you wanted to replace the characters a, b, and c, you would use the regex /[abc]/g.
You can use the snippet below. The regex pattern I used was /[[{(]/g. It may seem a bit overwhelming, but all it's doing is removing all the characters inside the bracket. Strip away the outside brackets and you get [{( which is the characters the regex will replace.
var text = "[fas[ds{ed[d{s(fasd[fa(sd"
console.log(text.replace(/[[{(]/g, ''));
For a project in my JavaScript class we're required to fetch a json object from flickr using their API defined by a set of tags the user enters; I've successfully done that, however I'd like to cover up a few cracks I've made while writing the algorithm.
For my search bar I'm checking:
($('#search').val().length == 0)
In order to make sure they have at least entered something. The problem I'm facing however is that if one is to type in spaces the spaces are still counted as characters.
My question is, is if I can do something like the following:
($('#search').trim().val().length == 0)
It seems, that this by itself doesn't work. Is there something I'm missing?
Any help would be much appreciated! Thanks!
trim() works on strings and removes leading and trailing spaces.
$('#search').trim().val().length
will try to execute trim() on object and thus will throw an error.
You first have to get the value(string) of the element and then trim it.
$('#search') // Select the element
.val() // Get it's value
.trim() // trim leading & trailing spaces
.length // Then get the length
or using jQuery $.trim()
$.trim($('#search').val()).length
Yes, you would want to run trim on the string not the DOM input so simply reverse it to:
($('#search').val().trim().length == 0)
Here is our text to replace:
<IMG src="https://domain.com/images/siteheader.jpg">
Using javascript .replace, we try to replace with blank space using the following:
.replace ("/<A href=\"http:\/\/domain.com\"><IMG src=\"https:\/\/domain.com\/images\/siteheader.jpg\"><\/A>/i"," ");
In all other browsers this seems to work, but not in IE. I even tried using this online regex validator: http://www.online-toolz.com/tools/regexp-editor.php and it says it's valid. Kind of stumped. Is IE doing something out of the norm?
You either use a string (the literal form of which looks like "...") or a regular expression (the literal form of which looks like /.../) with replace. You're trying to do both simultaneously. Remove the quotes:
.replace (/<A href="http:\/\/domain.com"><IMG src="https:\/\/domain.com\/images\/siteheader.jpg"><\/A>/i, " ");
When you use a string, it's just matched literally, no regular expression processing is done.
I haven't validated the entire contents of the regex, just removed the surrounding " and removed the \ in front of the embedded ".
Regexes are literals and should not have quotes around them:
.replace(/your regex here/,'replacement')
That being said, where is the text coming from? If it's coming from .innerHTML, browsers may return a string that is different from what you literally have in the source (for instance, attribute names may be uppercased, or the attributes themselves swapped. I believe older versions of IE strip out quotes around single-word attribute values, which would also mess with your regex.
In short, you should not use a regex for this. You could try this instead:
var toRemove = document.querySelector("a[href='http://domain.com']"),
parent = toRemove.parentNode;
parent.removeChild(toRemove);
I'm looking for a basic regex that removes any space. I want to use it for ZIP code.
Some people insert space after, before or in between the ZIP code.
I'm using /^\d{5}$/ now. I want to expand it to include space removal.
How can this be improved?
(I'm considering you want to remove spaces in your string, not verifying if it is valid even with spaces)
You can substitute one or more spaces (globally)
/\s+/g
by nothing.
zip.replace(/\s+/g, "");
Example in my browser's JS console:
> " 02 1 3 4".replace(/\s+/g, "");
"02134"
Here's a regex you can use instead of your current one to ignore any and all spaces.
/^(\s*\d){5}\s*$/
If you're sanitizing a form input or something, it's probably easiest to use:
zip = zip.replace(/\D/g,'');
you can then validate without a regex, just use the .length property on String.
if(zip.length != 5) alert('failed!');
I'm trying to remove a rectangular brackets(bbcode style) using javascript, this is for removing unwanted bbcode.
I try with this.
theString .replace(/\[quote[^\/]+\]*\[\/quote\]/, "")
it works with this string sample:
theString = "[quote=MyName;225]Test 123[/quote]";
it will fail within this sample:
theString = "[quote=MyName;225]Test [quote]inside quotes[/quote]123[/quote]";
if there any solution beside regex no problem
The other 2 solutions simply do not work (see my comments). To solve this problem you first need to craft a regex which matches the innermost matching quote elements (which contain neither [QUOTE..] nor [/QUOTE]). Next, you need to iterate, applying this regex over and over until there are no more QUOTE elements left. This tested function does what you want:
function filterQuotes(text)
{ // Regex matches inner [QUOTE]non-quote-stuff[/quote] tag.
var re = /\[quote[^\[]+(?:(?!\[\/?quote\b)\[[^\[]*)*\[\/quote\]/ig;
while (text.search(re) !== -1)
{ // Need to iterate removing QUOTEs from inside out.
text = text.replace(re, "");
}
return text;
}
Note that this regex employs Jeffrey Friedl's "Unrolling the loop" efficiency technique and is not only accurate, but is quite fast to boot.
See: Mastering Regular Expressions (3rd Edition) (highly recommended).
Try this one:
/\[quote[^\/]+\].*\[\/quote\]$/
The $ sign indicates that only the closing quote element at the end of the string should be used to determine the ending of the quote you're trying to remove.
And i added a "." before the asterisk so that this will match any sign in between. I tested this with your two strings and it worked.
edit: I don't exactly know how you are using that. But just as an addition. If you want the pattern also to match to a string where no attributes are added for example:
[quote]Hello[/quote]
You should change the "+" sign into an asterisk as well like this:
/\[quote[^\/]*\].*\[\/quote\]$/
This answer has flaws, see Ridgerunner's answer for a more correct one.
Here's my crack at it.
function filterQuotes(text)
{
return text.replace(/\[(\/)?quote([^\/]*)?\]/g,"");
}