Why String.indexOf check failed in JavaScript? - 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)

Related

Javascript Regex Search

I generated the following code through a website. What I am looking for is that the script scans through a text variable against a set of keywords, and if it finds any of the keywords, it passes it to a variable. And if two keywords are found, both are joined by a hyphen and passed to a variable. I also need to set the "var str" dynamically. For instance, "var str == VAR10." VAR10 will have a dynamic text to be searched for keywords.
var re = /Geo|Pete|Rob|Nick|Bel|Sam|/g;
var str = 'Sam maybe late today. Nick on call. ';
var m;
if ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
}
In the above code, Sam and Nick are two keywords that I want hyphenated and passed to VAR10.
If two keywords are found, both are joined by a hyphen and passed to a
variable
Try this update to your original code for clarity:
var re = /Geo|Pete|Rob|Nick|Bel|Sam/g;
var str = 'Sam maybe late today. Nick on call. ';
var m;
var VAR10 = ""; // holds the names found
if ((m = re.exec(str)) !== null) {
var name1 = m;
if ((m = re.exec(str)) !== null) {
var name2 = m;
// Two names were found, so hyphenate them
// Assign name1 + "-" + name2 to the var that you want
VAR10 = name1 + "-" + name2;
} else {
// In the case only one name was found:
// Assign name1 to the var that you want
VAR10 = name1;
}
}
Note, change
var re = /Geo|Pete|Rob|Nick|Bel|Sam|/g;
to
var re = /Geo|Pete|Rob|Nick|Bel|Sam/g;
Here is an updated demo: http://jsfiddle.net/7zg2hnt6/1/
You can "capture" names with parenthesis:
/(Geo|Pete|Rob|Nick|Bel|Sam)/g
A sample: https://regex101.com/r/eK5hY2/1
To return the first two names found in hyphenated fashion:
str.match(re) . slice(0, 2) . join('-')
You have an extra | at the end of your regexp, which is likely to result in matches on an empty string. Remove it.
I also need to set the "var str" dynamically. For instance, "var str == VAR10." VAR10 will have a dynamic text to be searched for keywords.
var str == VAR10 is invalid syntax. I'll assume you mean var str = VAR10;. That's just a plain old variable assignment. All assignments in JS are "dynamic" by definition and happen at run-time. This would seem to have nothing to do with your specific problem.
Your code is almost doing what you want.
First you need to capture your matches, then join them.
http://jsfiddle.net/c6tjk21d/1/
var re = /(Geo|Pete|Rob|Nick|Bel|Sam)/g;
var str = 'Sam maybe late today. Nick on call. ';
var VAR10 = str.match(re).join('-')
console.log(VAR10);
I don't think you want to use exec because it maintains state and I've found it to be unintuitive. For example, in order to get more than one match with the code you've written, you'll need to loop through resulting on exec. Check out MDN for examples if you're interested. I almost always prefer match().

I need to run a function if the URL has a specific string that can also come up as part of another string using jQuery or Javascript

I need to write a function to perform an action only if the URL has a specific string. The issue that I am finding is that the string can come up in multiple instances as part of another string. I need the function to run when the string is ONLY "?page=1". What I am finding is that the function is also being run when the string contains a string like "?page=10" , "?page=11" , "?page=12" , etc... I only need it to be done if the string is "?page=1" - that's it. How do I do that? I've tried a couple of different ways, but it does not work. Any help is appreciated. Here is the latest code that I have used that is close...but no cigar.
var location = window.location.href;
if (location.indexOf("?page=1") > -1){
//Do something
};
?page is a GET parameter. It doesn't necessarily have to be first in the URL string. I suggest you properly decode the GET params and then base your logic on that. Here's how you can do that:
function unparam(qs) {
var params = {},
e,
a = /\+/g,
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); };
while (e = r.exec(qs)) {
params[d(e[1])] = d(e[2]);
}
return params;
}
var urlParams = unparam(window.location.search.substring(1));
if(urlParams['page'] == '1') {
// code here
}
Alternatively, a regex with word boundaries would have worked:
if(/\bpage=1\b/.test(window.location.search)) {
// code here
}
if(location .indexOf("?page=1&") != -1 || (location .indexOf("?page=1") + 7 == i.length) ) {
}
You could look at the character immediately following the string "?page=1" in the url. If it's a digit,you don't have a match otherwise you do. You could trivially do something like this:
var index = location.indexOf("?page=1"); //Returns the index of the string
var number = location.charCodeAt(index+x); //x depends on the search string,here x = 7
//Unicode values for 0-9 is 48-57, check if number lies within this range
Now that you have the Unicode value of the next character, you can easily deduce if the url contains the string you require or not. I hope this points you in the right direction.

Regex to get string in URL before optional character

I have a URL which may be formatted like this: http://domain.com/space/all/all/FarmAnimals
or like this: http://domain.com/space/all/all/FarmAnimals?param=2
What regular expression can I use to return the expression FarmAnimals in both instances?
I am trying this:
var myRegexp = /\.com\/space\/[a-zA-Z0-9]*\/[a-zA-Z0-9]*\/(.*)/;
var match = myRegexp.exec(topURL);
var full = match[1];
but this only works in the first instance, can someone please provide an example of how to set up this regex with an optional question mark closure?
Thank you very much!
/[^/?]+(?=\?|$)/
Any non-/ followed by either ? or and end-of-line.
I wouldn't write my own regex here and let the Path class handle it (if those are your two string formats).
string url = "http://domain.com/space/all/all/FarmAnimals";
//ensure the last character is not a '/' otherwise `GetFileName` will be empty
if (url.Last() == '/') url = url.Remove(url.Length - 1);
//get the filename (anything from FarmAnimals onwards)
string parsed = Path.GetFileName(url);
//if there's a '?' then only get the string up to the '?' character
if (parsed.IndexOf('?') != -1)
parsed = parsed.Split('?')[0];
You could use something like this:
var splitBySlash = topURL.split('/')
var splitByQ = splitBySlash[splitBySlash.length - 1].split('?')
alert(splitByQ[0])
Explanation:
splitBySlash will be ['http:','','domain.com', ... ,'all','FarmAnimals?param=2'].
Then splitByQ will grab the last item in that array and split it by ?, which becomes ['FarmAnimas','param=2'].
Then just grab the first element in that.
This
.*\/(.*?)(\?.*)?$
Should capture the part of the string you are looking for as the group 1 (and the query after ? in group 2, if needed).
var url = 'http://domain.com/space/all/all/FarmAnimals?param=2';
//var url = 'http://domain.com/space/all/all/FarmAnimals';
var index_a = url.lastIndexOf('/');
var index_b = url.lastIndexOf('?');
console.log(url.substring(index_a + 1, (index_b != -1 ? index_b : url.length)));

RegEx get value from _GET request

I'll read more about RegEx in near future, but for now i can't get RegEx for the following:
?filter=aBcD07_1-&developer=true
Need to get only aBcD07_1-, without other.
Can you please help and provide me a RegEx for javascript
Thanks!
A simple substring and indexOf should do the trick.
var startIndex = str.indexOf('filter=') + 7;
str.substring(startIndex, str.indexOf('&', startIndex)); // returns "aBcD07_1"
Try with this one:
var rx = /[?&]filter=([a-zA-Z0-9_-]+).*/g;
var result = rx.exec(yourGetStr);
if (result && result.length == 2) {
alert (result[1]);
}
This regular expression will work even when filter is not the first query parameter.

JavaScript indexOf() - how to get specific index

Let's say I have a URL:
http://something.com/somethingheretoo
and I want to get what's after the 3rd instance of /?
something like the equivalent of indexOf() which lets me input which instance of the backslash I want.
If you know it starts with http:// or https://, just skip past that part with this one-liner:
var content = aURL.substring(aURL.indexOf('/', 8));
This gives you more flexibility if there are multiple slashes in that segment you want.
let s = 'http://something.com/somethingheretoo';
parts = s.split('/');
parts.splice(0, 2);
return parts.join('/');
Try something like the following function, which will return the index of the nth occurrence of the search string s, or -1 if there are n-1 or fewer matches.
String.prototype.nthIndexOf = function(s, n) {
var i = -1;
while(n-- > 0 && -1 != (i = this.indexOf(s, i+1)));
return i;
}
var str = "some string to test";
alert(str.nthIndexOf("t", 3)); // 15
alert(str.nthIndexOf("t", 7)); // -1
alert(str.nthIndexOf("z", 4)); // -1
var sub = str.substr(str.nthIndexOf("t",3)); // "test"
Of course if you don't want to add the function to String.prototype you can have it as a stand-alone function by adding another parameter to pass in the string you want to search in.
If you want to stick to indexOf:
var string = "http://something/sth1/sth2/sth3/"
var lastIndex = string.indexOf("/", lastIndex);
lastIndex = string.indexOf("/", lastIndex);
lastIndex = string.indexOf("/", lastIndex);
string = string.substr(lastIndex);
If you want to get the path of that given URL, you can also use a RE:
string = string.match(/\/\/[^\/]+\/(.+)?/)[1];
This RE searches for "//", accepts anything between "//" and the next "/", and returns an object. This object has several properties. propery [1] contains the substring after the third /.
Another approach is to use the Javascript "split" function:
var strWord = "me/you/something";
var splittedWord = strWord.split("/");
splittedWord[0] would return "me"
splittedWord[1] would return "you"
splittedWord[2] would return "something"
It sounds like you want the pathname. If you're in a browser, keep an a element handy...
var _a = document.createElement('a');
...and let it do the parsing for you.
_a.href = "http://something.com/somethingheretoo";
alert( _a.pathname.slice(1) ); // somethingheretoo
DEMO: http://jsfiddle.net/2qT9c/
In your case, you could use the lastIndexOf() method to get the 3rd forward slash.
Here's a very cool way of handling this:
How can I remove all characters up to and including the 3rd slash in a string?
My preference of the proposed solutions is
var url = "http://blablab/test/page.php";
alert(url.split("/")[3]);
//-> "test"
Inestead of using indexOf it is possible to do this this way:
const url = 'http://something.com/somethingheretoo';
const content = new URL(url).pathname.slice(1);

Categories