jQuery String Contains Manipulation? - javascript

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

Related

Checking the number inside a string in javascript

I have a string, say
var Str = 'My name is 123 and my name is 234'.
Now I split this as
var arrStr = Str.split(' ');
I iterate through the array and have different logic depending upon whether the word is a string or number. How do i check that? I tried typeof which didn't work for me.
EDIT:
After Seeing multiple answers. Now, I am in despair, which is the most efficient way?
If you care only about the numbers, then instead of using split you can use a regular expression like this:
var input = "My name is 123 and my name is 234";
var results = input.match(/\d+/g)
If you care about all pieces, then you can use another expression to find all non-space characters like this:
var input = "My name is 123 and my name is 234";
var results = input.match(/\S+/g)
Then iterate them one by one, and check if a given string is a number or not using the famous isNumeric() function posted by #CMS in this famous question.
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
NOTE: Thanks to #Pointy and if you want them as numbers, input.match(/\d+/g).map(Number).
You need to attempt to convert your array values to an integer.
To iterate them you can use a for loop:
for(i=0;i<arrStr.length;i++) {
var result = !isNaN(+arrStr[i]) ? 'number' : 'string';
console.log(result);
}
Here I'm using a unary + to attempt to convert the value of each array value to a number. If this fails, the result will be NaN. I'm then using JavaScript's isNaN() method to test if this value is NaN. If it isn't, then it's a number, otherwise it's a string.
The result of this using the string you've provided is:
string
string
string
number
string
string
string
string
number
To use this in an if statement, we can simply:
for(i=0;i<arrStr.length;i++) {
if(isNaN(+arrStr[i])) {
/* Process as a string... */
}
else {
/* Process as a number... */
}
}
JSFiddle demo.
To expound on Sniffer's answer...
var input = "My name is 123 and my name is 234";
var numberArray = input.match(/\d+/g);
var wordArray = input.match(/[A-Za-z]+/g);
for (var number in numberArray)
{
//do something
}
for (var word in wordArray)
{
//do something
}
While researching, I found out about the Number() object. This is generally used to work with manipulation of numbers. MDN has a good documentation .
I found out that Number() returns NaN (Not a Number) when not passed a number. Since no number returns NaN, It could be a good way to check whether the passed object is string or a number literal.
So my code would be:
if (Number(arrStr[i]) == NaN){
//string
} else {
//number
}

javascript regular expression .search

i have a little problem with .search
this is the code
// filter - posts
jQuery('.filter_by').live('click',function(){
var target_fi = jQuery(this);
var target_cat = target_fi.parents('.cat').children('.namechanger').val();
target_fi.next().fadeIn(100);
var cat_all = target_fi.prev().find("option").each(function(i){
if(jQuery(this).attr('data-cats').search(target_cat) == -1){
jQuery(this).css({"display":"none"});
}
});
});
I want to use the variable target_cat with .search
I can't do this .search(/target_cat/)
If you want to make a regular expression out of the string value of target_cat, then you can do this:
var mySearchTerm = new RegExp(target_cat);
...
if(jQuery(this).attr('data-cats').search(mySearchTerm) == -1){
You need to create RegExp object and pass that to search method
if(jQuery(this).attr('data-cats').search(new RegExp(target_cat)) == -1 )){
...
}
To convert anything into a regular expression, simply drop it into the constructor:
var something = "foobar";
var expression = new RegExp(something, 'i');
note the second argument for flags. See RegExp for more info on the constructor and Regular Expressions for details on how things work.
If your something contains "special characters" (such as |, ?, {) you need to escape them, if you want them to be meant literally (/foo?/ vs. /foo\?/). Here's a function that'll esacpe all relevant characters for you:
function escapeRegEx(string) {
return string.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
You are using jQuery.live, but should use jQuery.on instead
You are using .search() when .match() suffices
You are using the explicit jQuery(this).css({"display":"none"}); when jQuery(this).hide(); suffices
note that you are repeating jQuery(this) in your loop - one should be enough - variables are your friends.

Regex - Regular expression pattern failing on URL GET parameter

I'm trying to do a URL GET variable replace, however the regular expression for checking whether the variable exists in amongst other GET variables is returning true when I am expecting it to return false.
The pattern I am using is: &sort=.*&
Test URL: http://localhost/search?location=any&sort=asc
Am I right to believe that this pattern should be returning false on the basis that their is no ampersand character following the sort parameter's value?
Full code:
var sort = getOptionValue($(this).attr('id'));
var url = document.URL;
if(url.indexOf('?') == -1) {
url = url+'?sort='+sort;
} else {
if(url.search('/&sort=.*&/i')) {
url.replace('/&sort=.*&/i','&sort='+sort+'&');
}
else if(url.search('/&sort=.*/i')) {
url.replace('/&sort=.*/i','&sort='+sort);
}
}
Am I right to believe that this pattern should be returning false on the basis that their is no ampersand character following the sort parameter's value?
Well, you are using String.search, which, according to the linked documentation:
If successful, search returns the index of the regular expression inside the string. Otherwise, it returns -1.
So it will return -1, or 0 or greater when there is a match. So you should test for -1, not truthiness.
Also, there is no need to pass the regexes as strings, you might as well use:
url.replace(/&sort=.*&/i,'&sort='+sort+'&');
Further, keep in mind that replace will create a new string, not replace in the string (strings in Javascript are immutable).
Finally, I don't see the need for searching for the string, and then replacing it -- it seems that you always want to replace &sort=SOMETHING with &sort=SOMETHING_ELSE, so just do that:
if(url.indexOf('?') == -1) {
url = url+'?sort='+sort;
} else {
url = url.replace(/&sort=[^&]*/i, '&sort=' + sort);
}
The javascript string function search() returns -1 if not found, not false. Your code should read:
if(url.search('/&sort=.*&/i') != -1) {
url.replace('/&sort=.*&/i','&sort='+sort+'&');
}
else if(url.search('/&sort=.*/i') != -1) {
url.replace('/&sort=.*/i','&sort='+sort);
}
You should check
if(url.search('/&sort=.*&/i') >= 0)
then it should work
You could use this code
var url = 'http://localhost/search?location=any&sort=asc';
var vars = {};
var parts = url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
console.log(vars);
//vars is an object with two properties: location and sort
This can be done by using
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + sort);
The match broken down
Group 1 matches for ? or &
Group 2 matches sort=
Group 3 matches anything that is not a & or ?
Then "$1$2" + sort will replace all 3 group matches with the first 2 + your variable
examples using string "REPLACE" instead of your sort variable
url = "http://localhost/search?location=any&sort=asc&a=z"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?location=any&sort=REPLACE&a=z"
url = "http://localhost/search?location=any&sort=asc"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?location=any&sort=REPLACE"
url = "http://localhost/search?sort=asc"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?sort=REPLACE"
url = "http://localhost/search?sort=asc&z=y"
url.replace(/([?&])(sort=)([^&?]*)/, "$1$2" + "REPLACE");
// => "http://localhost/search?sort=REPLACE&z=y"
The pattern I am using is: &sort=.*& Test URL:
http://localhost/search?location=any&sort=asc
Am I right to believe that this pattern should be returning false on
the basis that their is no ampersand character following the sort
parameter's value?
you are assuming right. But in your code you have else if(url.search('/&sort=.*/i')) which will match and thus still replace the value.
You should also note that your code would turn http://localhost/search?sort=asc&location=any&some=more into http://localhost/search?sort=asc&some=more. that's because because .* is greedy (trying to match as much as possible). You can avoid that by telling it to match as little as possible by appending a ? like so .*?.
That said, I believe you may be better off with a library that knows how URLs actually work. You're not compensating for parameter position, possible escaped values etc. I suggest you have a look at URI.js and replace your wicked regex with
var uri = URI(document.URL),
data = uri.query(true);
data.foo = 'bazbaz';
uri.query(data);

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

How to know if JavaScript string.replace() did anything?

The replace function returns the new string with the replaces, but if there weren't any words to replace, then the original string is returned. Is there a way to know whether it actually replaced anything apart from comparing the result with the original string?
A simple option is to check for matches before you replace:
var regex = /i/g;
var newStr = str;
var replaced = str.search(regex) >= 0;
if(replaced){
newStr = newStr.replace(regex, '!');
}
If you don't want that either, you can abuse the replace callback to achieve that in a single pass:
var replaced = false;
var newStr = str.replace(/i/g, function(token){replaced = true; return '!';});
As a workaround you can implement your own callback function that will set a flag and do the replacement. The replacement argument of replace can accept functions.
Comparing the before and after strings is the easiest way to check if it did anything, there's no intrinsic support in String.replace().
[contrived example of how '==' might fail deleted because it was wrong]
Javascript replace is defected by design. Why? It has no compatibility with string replacement in callback.
For example:
"ab".replace(/(a)(b)/, "$1$2")
> "ab"
We want to verify that replace is done in single pass. I was imagine something like:
"ab".replace(/(a)(b)/, "$1$2", function replacing() { console.log('ok'); })
> "ab"
Real variant:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
return "$1$2";
})
> ok
> "$1$2"
But function replacing is designed to receive $0, $1, $2, offset, string and we have to fight with replacement "$1$2". The solution is:
"ab".replace(/(a)(b)/, function replacing() {
console.log('ok');
// arguments are $0, $1, ..., offset, string
return Array.from(arguments).slice(1, -2)
.reduce(function (pattern, match, index) {
// '$1' from strings like '$11 $12' shouldn't be replaced.
return pattern.replace(
new RegExp("\\$" + (index + 1) + "(?=[^\\d]|$)", "g"),
match
);
}, "$1$2");
});
> ok
> "ab"
This solution is not perfect. String replacement itself has its own WATs. For example:
"a".replace(/(a)/, "$01")
> "a"
"a".replace(/(a)/, "$001")
> "$001"
If you want to care about compatibility you have to read spec and implement all its craziness.
If your replace has a different length from the searched text, you can check the length of the string before and after. I know, this is a partial response, valid only on a subset of the problem.
OR
You can do a search. If the search is successfull you do a replace on the substring starting with the found index and then recompose the string. This could be slower because you are generating 3 strings instead of 2.
var test = "Hellllo";
var index = test.search(/ll/);
if (index >= 0) {
test = test.substr(0, index - 1) + test.substr(index).replace(/ll/g, "tt");
}
alert(test);
While this will require multiple operations, using .test() may suffice:
const regex = /foo/;
const yourString = 'foo bar';
if (regex.test(yourString)) {
console.log('yourString contains regex');
// Go ahead and do whatever else you'd like.
}
The test() method executes a search for a match between a regular expression and a specified string. Returns true or false.
With indexOf you can check wether a string contains another string.
Seems like you might want to use that.
have a look at string.match() or string.search()
After doing any RegExp method, read RegExp.lastMatch property:
/^$/.test(''); //Clear RegExp.lastMatch first, Its value will be ''
'abcd'.replace(/bc/,'12');
if(RegExp.lastMatch !== '')
console.log('has been replaced');
else
console.log('not replaced');

Categories