How to find a text using javascript or jquery. - javascript

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

Related

How to get all value of invalid characters in a string in jquery?

I have a jquery method that check special character as shown below:
function checkForSpecialChar(val) {
if (val != 0 && /^[a-zA-Z0-9- ]*$/.test(val) == false) {
return false;
}
return true;
}
This is working fine as it validate the value correctly.
However now I need to get all invalid characters for the val string and show it to the user.
So for example if val is = 123gdf$£!
It should get only the invalid character which is $£!.
Any idea how i can do that please?
Thanks in advance for any help.
Just invert your regex by adding ^ inside []
[^a-zA-Z0-9- ] // match anything that is not alphanumerical, `-` or whitespace
alert(
'Invalid characters of "123gdf$£!": '
+ (
'123gdf$£!'.match(/[^a-zA-Z0-9- ]/g)
.join('')
)
);
Try this
var val = "123gdf$£!".replace(new RegExp("[0-9a-zA-Z]", "g"), "");
https://jsfiddle.net/wx38rz5L/1816/
Simply you can use string match() method of javascript.
Here it is:
var val= "123gdf$£!";
var result= str.match(/^[a-zA-Z0-9- ]*$/);
result will be an array with values.

jquery text() compare to string

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");
}

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('')
;

javascript - replacing spaces with a string

I'm new to Javascript and need a bit of help with program on a college course to replace all the spaces in a string with the string "spaces".
I've used the following code but I just can't get it to work:
<html>
<body>
<script type ="text/javascript">
// Program to replace any spaces in a string of text with the word "spaces".
var str = "Visit Micro soft!";
var result = "";
For (var index = 0; index < str.length ; index = index + 1)
{
if (str.charAt(index)= " ")
{
result = result + "space";
}
else
{
result = result + (str.charAt(index));
}
}
document.write(" The answer is " + result );
</script>
</body>
</html>
For
isn't capitalized:
for
and
str.charAt(index)= " "
needs to be:
str.charAt(index) == " "
JavaScript Comparison Operators
for loops
As others have mentioned there are a few obvious errors in your code:
The control flow keyword for must be all lower-case.
The assignment operator = is different than the comparison operators == and ===.
If you are allowed to use library functions then this problem looks like a good fit for the JavaScript String.replace(regex,str) function.
Another option would be to skip the for cycle altogether and use a regular expression:
"Visit Micro soft!".replace(/(\s)/g, '');
Try this:
str.replace(/(\s)/g, "spaces")
Or take a look at this previous answer to a similar question: Fastest method to replace all instances of a character in a string Hope this help
You should use the string replace method. Inconvenienty, there is no replaceAll, but you can replace all anyways using a loop.
Example of replace:
var word = "Hello"
word = word.replace('e', 'r')
alert(word) //word = "Hrllo"
The second tool that will be useful to you is indexOf, which tells you where a string occurs in a string. It returns -1 if the string does not appear.
Example:
var sentence = "StackOverflow is helpful"
alert(sentence.indexOf(' ')) //alerts 13
alert(sentence.indexOf('z')) //alerts -1

jQuery String Contains Manipulation?

In most languages like C# for example given a string you can test (boolean) if that string contains another string, basically a subset of that string.
string x = test2;
if(x.contains("test"))
// do something
How can I do this in a simple way with Javascript/Jquery?
This is done with indexOf, however it returns -1 instead of False if not found.
Syntax
string.indexOf(searchValue[, fromIndex])
Parameters
searchValue -
A string representing the value to search for.
fromIndex -
The location within string to start the search from. It can be any integer between 0 and the length of string. The default value is 0.
Return
The first index in string at which the start of the substring can be found, or -1 if string does not contain any instances of the substring.
As Paolo and cletus said, you can do it using indexOf().
Valid to mention is that it is a javascript function, not a jQuery one.
If you want a jQuery function to do this you can use it:
jQuery.fn.contains = function(txt) { return jQuery(this).indexOf(txt) >= 0; }
The indexOf operator works for simple strings. If you need something more complicated, it's worth pointing out that Javascript supports regular expressions.
A simple contains can also be useful for example:
<div class="test">Handyman</div>
$(".test:contains('Handyman')").html("A Bussy man");
A working example, using just indexOf and jQuery
// Add span tag, if not set
$(document).ready(function(c) {
$('div#content ul.tabs li a').each(function(c){
// Add span wrapper if not there already
if( $(this).html().indexOf('span') == -1){
$(this).html('<span class="tab">' + $(this).html() + '</span>');
}
});
});
DT
Try to implement this
function function1() {
var m = document.all.myDiv.contains(myB);
if (m == true){
m = "YES"
} else {
m = "NO"
}
alert(m)
}

Categories