I got 2 variables;
value = 'com';
longString= "com-233-123-232-123";
I'd like to check if "value" is inside "longString". I tried using regex with test() but I fail, maybe you know better.
I think the indexOf(substr, [start]) is enough no need to regex.
indexOf(substr, [start])
Searches and (if found) returns the index number of the searched character or substring within the string. If not found, -1 is returned. "Start" is an optional argument specifying the position within string to begin the search. Default is 0.
http://www.javascriptkit.com/javatutors/string4.shtml
Two ways
1st indexOf
if (longString.indexOf(value) != -1)
// found
else
// not found
2nd split
var value = 'com'; var longString= "com-233-123-232-123";
var split1=longString.split("-");
var i=0;
var found=0;
while (i<split1.length)
{
if(split1[i]==value)
{
found=1;
break;
}
i++;
}
if(found==1)
//found
else
//not found
Don't use regular expressions for this - if the value you're looking for can be interpreted as a regular expression itself then you'll have trouble. Just check for longString.indexOf(value) != -1.
What does jQuery has to do with this? This is a simple Javascript problem
if (longString.indexOf(value) != -1)
// We found it
else
// We didn't find it
Related
I would like to find out the length of the variable which I get from the screen. If I use
var driverID = element(by.id('driverID')).getAttribute('value')
driverID.length
it is throwing and error as Property 'length' does not exist on type'Promise <string>. Can some one help me in finding the length of the string.
I would also like to know how to use string operations in protractor tests. In this case I want to know, if the string first index is 'character or a number' and the second index is 'character or a number'. I want to do this by using the length of the string.
use the count() method for the number of elements inside a Promise.
Now for your specific problem, you should do something like:
element(by.id('driverID')).getAttribute('value').then(function(attr) {
var length = attr.length; // I don't really need why you need this length
if (!isNaN(attr[0]) && !isNaN(attr[1])) {
// 1st and 2nd characters of the string are numbers.
}
})
try that:
var driverID = element(by.id('driverID')).getAttribute('value');
driverID.then((attribute) => {
console.log(attribute.length)
});
the second issue you can resolve using regex
I'm using Google map to get distance and time between two locations.
this works fine...
however, I would like to replace some texts/words that has been spit out on my page from google map api with my own texts/words.
for example: I would like to replace the about with ETA:
This is my javascript code to replace the word:
<script>
function myFunction() {
var str = document.getElementsByClassName("adp-summary").innerHTML;
var res = str.replace("about", "ETA: ");
document.getElementsByClassName("adp-summary").innerHTML = res;
}
</script>
but unfortunately this doesn't do anything and it doesn't replace the word about with ETA:.
Here is my entire code:
http://jsfiddle.net/dvw37ktu/1/
Could someone please advise on this issue?
Thanks in advance.
As mentioned in the comments, document.getElementsByClassName is returning a HTMLCollection that matches your selector, which is why you can't set the .innerHTML. This can be fixed by dealing with the collection, say, by looping over it:
var adpSummary = document.getElementsByClassName("adp-summary");
for (var i = 0; i < adpSummary.length; i++) {
// Do string replacement on adpSummary[i]
adpSummary[i].innerHTML = adpSummary[i].innerHTML.replace(new RegExp('about', 'gm'), 'ETA: ')
}
if only using native js, replace only replaces the first instance of the string.
you can either loop while index check:
while(str.indexOf("about") > -1)
{
//do replace here
}
or a better option is to use a regex.
see more here:
Why does javascript replace only first instance when using replace?
if(kword == term){
$(this).trigger('click');
}
The case is if the kword is "car" and the term is "cars", I would want that to be a positive match.
Currently I'm looking at an exact match. As I'm a novice at jquery I don't know how to do this. Can anyone point me to the right direction?
You can use indexOf() to find the string inside another
if(term.indexOf(kword)>-1){
//code
}
If you need to simply compare a string variable with a different string variable with an 's' in the end, you can go with following code:
if (term === kword + 's') {
...
}
If you need to check specifically if terms is a plural version of kword, you would need much larger implementation, featuring pluralize function (that you need to implement or search for a library):
if (term === pluralize(kword)) {
...
}
function pluralize(word) {
//implement function
}
If that doesn't not answer your question, please be more clear about what you need to do.
As #Anton said, you can use indexOf(), it returns the position of the first occurrence of a specified value in a string otherwise returns -1 if the value to search for never occurs. Also note that this method is case sensitive.
I need to identify list (li) items that include a full stop at the very end.
I can work out how to match a full string with
if ($(obj).elements[0].innerHTML === "This list has full stops."
but don't know how to match just a full stop at the end. I tried
if ($(obj).elements[0].innerHTML === "*."
but no good.
Please help
if (/.*?\.$/.test($(obj).elements[0].innerHTML) {}
Not a big fan of regex, however if you want to do the above thing multiple times and make code easily readable you can create a function for it.
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
And use it like this:
var str = $(obj).elements[0].innerHTML;
if(endsWith(str,'.')){
// Do watever.
}
I am looking to find the best possible way to find how many $ symbols are on a page. Is there a better method than reading document.body.innerHTML and calc how many $-as are on that?
Your question can be split into two parts:
How can we get the the webpage text content without HTML tags?
We can generalize the second question a bit.
How can we find the number of string occurrences in another string?
And the 'best possible way to do this':
Amaan got the idea right of finding the text, but lets take it further.
var text = document.body.innerText || document.body.textContent;
Adding textContent to the code helps us cover more browsers, since innerText is not supported by all of them.
The second part is a bit trickier. It all depends on the number of '$' symbol occurrences on the page.
For example, if we know for sure, that there is at least one occurrence of the symbol on the page we would use this code:
text.match(/\$/g).length;
Which performs a global regular expression match on the given string and counts the length of the returned array. It's pretty fast and concise.
On the other hand, if we're not sure if the symbol appears on the page at least once, we should modify the code to look like this:
if (match = text.match(/\$/g)) {
match.length;
}
This just checks the value returned by the match function and if it's null, does nothing.
I would recommend using the third option only when there is a large occurrence of the symbols in the page or you're going to perform the search many many times. This is a custom function (taken from here) to count the occurrence of the specified string in another string. It performs better than the other two, but is longer and harder to understand.
var occurrences = function(string, subString, allowOverlapping) {
string += "";
subString += "";
if (subString.length <= 0) return string.length + 1;
var n = 0,
pos = 0;
var step = (allowOverlapping) ? (1) : (subString.length);
while (true) {
pos = string.indexOf(subString, pos);
if (pos >= 0) {
n++;
pos += step;
} else break;
}
return (n);
};
occurrences(text, '$');
I'm also including a little jsfiddle 'benchmark' so you can compare these three different approaches yourself.
Also: No, there isn't a better way of doing this than just getting the body text and counting how many '$' symbols there are.
You should probably use document.body.innerText or document.body.textContent to avoid getting your HTML give you false positives.
Something like this should work:
document.body.innerText.match(/\$/g).length;
An alternate way I can think of, would be to use window.find like this:
var len = 0;
while(window.find('$') === true){
len++;
}
(This may be unreliable because it depends on where the user clicked last. It will work fine if you do it onload, before any user interaction.)