jquery text() compare to string - javascript

How to compare strings to jquery text()? I've tried this one but it will not work.
var str = 'hello';
var string = $(this).find("text").trim();
if(str == string)
{
string.css("visibility", "visible");
}
What's wrong with my code? Any idea please? thank you

If you want to use the text method you need to actually use it. Using find("text") would try fo find a <text> element inside the element, and there are no such elements.
Also, use the jQuery trim method as the string.trim method isn't available in all browsers. Apply the style to the element, not the string:
var str = 'hello';
var string = $.trim($(this).text());
if(str == string)
{
$(this).css("visibility", "visible");
}

Aren't you getting any error?
Usually calling .find on something will search for a DOM element. find is not for searching text.
With find("text") you are looking for elements in the DOM tree. And they don't have .trim() methods associated, so you should be getting an error like 'TypeError: undefined is not a function'
Maybe what you want to do is the following...
var string_elem = $(this),
str = 'hello',
string = string_elem.find("text").text().trim();
if(str === string) {
string_elem.css('visibility', 'visible');
}
Also, if you want your string comparison to be case insensitive you should do something like this
if(str.toLowerCase() === string.toLowerCase())

string is just a string, so you cannot .css();.
and better use some other variable name instead of string, this seems to be already reserved one.
try this
var str = 'hello';
var string = $(this).find("text").trim();
var string_elem = $(this);
if(str == string){
string_elem.css("visibility", "visible");
}

Related

How to replace specific parts in string with javascript with values from object

I want to make custom replacer method for my HTML output. But I can't figure it out. I guess it should be done with String.match and replace somehow.
I have some "error codes" in my string that always start with _err_ and I have a JS object with values.
What I want to achieve:
Find all string parts (error codes) that starts with _err_
Get correct key for my object - error code without _err_
Find value from Lang object
Replace error code with correct Lang value.
Some error codes may appear multiple times.
var content = "Looks like you have _err_no_email or _err_no_code provided";
var Lang = {
'no_email' : "No email",
'no_code' : "No code"
};
I can do it other way around. So I cycle the Lang object and replace those in string.
It would be something like this if using underscore:
function replaceMe() {
_.each(Lang, function(value, key) {
content = content.replace(new RegExp('_err_' + key,'g'), value);
});
console.log(content);
};
But if it can be done faster with my first idea then I want to know how.
A simple regex should do the trick:
var content = content.replace(/\b_err_(.+?)\b/g, function(match, errorName) {
return Lang[errorName] || match;
});
This assumes that you do not want strings like "blah_err_blah" to be replaced, and defaults to not replacing the text if the error cannot be found in your Lang object.
var replace = function(str, object, regexp) { //if property not found string is not replaced
return String(str).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name) {
return (object[name] != null) ? object[name] : match;
});
}
This is a format function I've used in several projects thats quite efficient. Matches {prop} by default to {prop:'val'} but you can pass a regex for example maybe in your case /_err_+\S/g so it matches other tokens in your string.
So you can do:
var content ="Looks like you have {no_email} or {no_code} provided";
var Lang = {
'no_email' : "No email",
'no_code' : "No code"
}
var formatted = replace(content, lang);
Or for your original string stealing the other answers regex:
var formatted = replace(content, lang, /_err_([^\s]+)/g)
You can use a callback function, that look if a key matching the error code exists in your Lang object, and if so returns the value of that (and otherwise just the key itself, thereby doing no replacement, like so:
content.replace(/_err_([a-z_]+)/gi, function(fullmatch, key) {
return Lang[key] ? Lang[key] : fullmatch;
});
The first parameter passed to the function will be the full match, and the second parameter key will just be that part grouped by the bracktes.
And then, if Lang contains a (non-falsy) value for key, that’ll be returned, otherwise just the fullmatch value, so that that part of the string gets “replaced” with itself.
See it in action here: http://jsfiddle.net/VZVLt/1/
One more variation with split
content = content
.split('_err_')
.map(function(str, index){
if (index === 0)
return str;
var whitespace = str.indexOf(' '),
key = str.substring(0, whitespace)
return Lang[key] + str.substring(whitespace);
})
.join('')
;

Why String.indexOf check failed in JavaScript?

From this famous high-voted question I've find an effective way to check if a string contains another string or not with String.indexOf.
var abcde = "abcdefg";
var abc = "abc";
alert(abc.indexOf(abcde) != -1);//return true
But when I try to do like this:
var url = "https://stackoverflow.com/questions/1789945/method-like-string-contains-in-javascript";
var s = "stackoverflow";
alert(s.indexOf(url) != -1); //**return false,but I think it 'should' return true!**
I'm curious that why a more complex which contains symbol or slash / seems to be failed. Or did I miss something?
The string you search is the parameter, not the receiver.
Change
alert(s.indexOf(url) != -1);
to
alert(url.indexOf(s) != -1);
(and you should also use console.log instead of alert, for your own comfort)

How to find a text using javascript or jquery.

I need to find a text from a paragraph using java script.
Is there any code in JavaScript like we do in c# to find a text using "string.Contains("")" method.
Pls help...
Thanks Guys..
You can use str.search()
It will return the position of match and -1 if not found
http://www.w3schools.com/jsref/jsref_search.asp
equivalent of string.Contains("") is indexOf (returns -1 if subString doesnt exist in a string).
you can do :
var myString = "foo";
var myParagraphText = $('#myParagraphId').text();
if(myParagraphText.indexOf(myString) != -1){
//myParagraphText contains myString
}
you can use string.indexOf("text") method which will return index of the "text" in the "string", return -1 if the text not found in the string.
var n = $('p').text();
var regex = new RegExp('text to search for', "i");
if(regex.exec(n) != null) {
// text found
} else {
//text not found
}
Use the search() function
If it returns -1, the string is not present
Non-negative number means, string is present
var str="hello there";
alert(str.search("there"));
For searching text inside a block element .
var str="your block"
str.search("text to find");
str.indexOf("text to find");
return the index of the text

javascript - replacing text not between in attributes

I'm trying to replace text inside an HTML string with Javascript.
The tricky part is that I need to replace the text only if it isn't inside a tag (meaning it's not part of an attribute):
var html_str = '<div>hi blah blah<img src="img.jpg" alt="say hi" />hi!</div>';
In this example, after I do html_str.replace("hi","hello"); I want to replace only the text inside the div and a tags, avoiding the <img alt=".." or the href="....
Some more info:
html_str = document.body.innerHTML;, therefore the elements are unknown. The example above is only an example.
Regex are more than welcome.
The hi and hello values are inside varaibles, meaning the actual replace is like so: html_str.replace(var1,var2);
The REAL code is this:
var html_str = document.body.innerHTML;
var replaced_txt = "hi";
var replace_with = "hello";
var replaced_html = html_str.replace(replaced_txt,replace_with);
I hope I explained myself well.
Thanks in advance.
This maybe?
var obj = {'hi':'hello','o':'*','e':'3','ht':'HT','javascrpit':'js','ask':'ASK','welcome':'what\'s up'}; // This may contain a lot more data
(function helper(parent, replacements) {
[].slice.call(parent.childNodes, 0).forEach(function (child) {
if (child.nodeType == Node.TEXT_NODE) {
for (var from in replacements) {
child.nodeValue = child.nodeValue.replace(from, replacements[from]);
}
}
else {
helper(child, replacements);
}
});
}(document.body, obj));
http://jsfiddle.net/G8fYq/4/ (uses document.body directly)
If you want to make the changes visible immediately then you could also pass document.body and forget about the whole container stuff.
Update to allow for multiple replacements in one run.
You could also try XPath in javascript, though the following solution will not work in IE.
var
replacements = {'hi':'hello','o':'*','e':'3','ht':'HT','javascrpit':'js','ask':'ASK','welcome':'what\'s up'},
elements = document.evaluate('//text()', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null),
i = 0,
textNode, from;
for (; i < elements.snapshotLength; i += 1) {
textNode = elements.snapshotItem(i);
for (from in replacements) {
if (replacements.hasOwnProperty(from)) {
textNode.nodeValue = textNode.nodeValue.replace(from, replacements[from]);
}
}
}
Actually it is possible to use this simple regex negative lookahead:
(?![^<>]*>)
Just add it to your match pattern and it will exclude any content as attributes in tags. Here is an example:
Javascript regex: Find all URLs outside <a> tags - Nested Tags
You can try this, but regexp and HTML are not friends:
var str = '<div>hi blah blah<img src="img.jpg" alt="say hi" />hi!</div>',
rx = new RegExp('(\>[^\>]*)' + 'hi' + '([^\>=]*\<)', 'g');
str = str.replace(rx, '$1hello$2');

Removing string using javascript

I have a string like
var test="ALL,l,1,2,3";
How to remove ALL from string if it contains using javascript.
Regards,
Raj
you can use js replace() function:
http://www.w3schools.com/jsref/jsref_replace.asp
so:
test.replace("ALL,", "");
If the word All can appear anywhere or more than once (e.g. "l,1,ALL,2,3,ALL") then have such code:
var test = "l,1,ALL,2,3,ALL"
var parts = test.split(",");
var clean = [];
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if (part !== "ALL")
clean.push(part);
}
var newTest = clean.join(",");
After this the variable newTest will hold the string without ALL.
If all you want to do is remove occurrences of the string "ALL" from another string, you can use the JavaScript String object's replace method:
test.replace("ALL","");
I'm not really sure if you want to remove all instances of capital letters from your string, but you are probably looking at using a regular expression such as s.replace(/[A-Z]/g,"") where s is the string.
Looking up javascript RegExp will give more indepth details.
use:
test.replace ( 'ALL,', '' );

Categories