JavaScript Replace function check - javascript

I am doing a java script replace as :
var featureTitle;
featureTitle = row.cells[1].text();
if (!featureTitle.indexOf('*') != -1)
{
featureTitle = featureTitle.replace('*', '');
}
Is if (!featureTitle.indexOf('*') != -1) needed check here??
OR replace will take care of it?

replace will do nothing if the asterisk does not exist, so it's safe to call without the check first.
Speaking of which, the check has a bug which makes the code as a whole behave incorrectly:
if (!featureTitle.indexOf('*') != -1) // what's that ! in front doing?
Since !featureTitle.indexOf('*') is always true or false, this condition will always succeed (both booleans compare unequal to -1).

Here is the referenced JSFiddle for you
if (!featureTitle.indexOf('*') != -1){...}
is not mandatory to place, you can do .replace() directly
var featureTitle;
featureTitle = row.cells[1].text();
featureTitle = featureTitle.replace('*', '');

There is no need of that if statement. I think .replace() will take care of it(if *exists it will replace it else no action). If you want to replace all the * in the string then use \g global attribute.
featureTitle = featureTitle.replace(/*/g,'');

replace will work on first occurence of '*'. If there is none, then nothing will be replaced, therefore "if" is not needed

Related

return true if only there is exact include

Using includes method we get true for all of these logs:
console.log("https://example.com/test/media/instructions/listen_again_long/1.mp3".includes('listen_again_long')); // true
console.log("https://example.com/test/media/instructions/listen_again_long/2.mp3".includes('listen_again')); // true
console.log("https://example.com/test/media/instructions/listen_again_long/3.mp3".includes('listen')); // true
But we know only the first log should return true because we have exactly listen_again_long inside the longer string.
if we consider this part fixed: https://example.com/test/media/instructions/
How we can only return true for the first one and false for the rest of the logs?
You are actually looking for a certain string enclosed in /, so one option would be to simply include both / in the argument you are passing to String.prototype.includes():
console.log("https://example.com/test/media/instructions/listen_again_long/1.mp3".includes('/listen_again_long/'));
console.log("https://example.com/test/media/instructions/listen_again_long/2.mp3".includes('/listen_again/'));
console.log("https://example.com/test/media/instructions/listen_again_long/3.mp3".includes('/listen/'));
You could also do the same thing using RegExps and RegExp.prototype.test():
console.log(/\/listen_again_long\//.test("https://example.com/test/media/instructions/listen_again_long/1.mp3"));
console.log(/\/listen_again\//.test("https://example.com/test/media/instructions/listen_again_long/2.mp3"));
console.log(/\/listen\//.test("https://example.com/test/media/instructions/listen_again_long/3.mp3"));
In both cases you could replace /listen_again_long/ with the whole thing if you want to make sure the match doesn't happen in a different place:
"...".includes("https://example.com/test/media/instructions/listen_again_long/");
Or, with RegExp:
/https:\/\/example.com\/test\/media\/instructions\/listen_again_long\//.test("...");
You'll have to extract the substring you want to compare against your parameter and then do a straight === comparison.
var url = <your passed in mp3 file>;
var s = "https://example.com/test/media/instructions/"
var substring = url.substring(url.indexOf(s) + url.length);
substring = substring.substring(0, url.indexOf("/");
substring === "listen_again_long"

How to access the first two digits of a number

I want to access the first two digits of a number, and i have tried using substring, substr and slice but none of them work. It's throwing an error saying substring is not defined.
render() {
let trial123 = this.props.buildInfo["abc.version"];
var str = trial123.toString();
var strFirstThree = str.substring(0,3);
console.log(strFirstThree);
}
I have tried the above code
output of(above code)
trial123=19.0.0.1
I need only 19.0
How can i achieve this?
I would split it by dot and then take the first two elements:
const trial = "19.0.0.1"
console.log(trial.split(".").slice(0, 2).join("."))
// 19.0
You could just split and then join:
const [ first, second ] = trial123.split('.');
const result = [ first, second ].join('.');
I have added a code snippet of the work: (explanation comes after it, line by line).
function getFakePropValue(){
return Math.round(Math.random()) == 0 ? "19.0.0.1" : null;
}
let trial123 = getFakePropValue() || "";
//var str = trial123.toString();
// is the toString() really necessary? aren't you passing it along as a String already?
var strFirstThree = trial123.split('.');
//var strFirstThree = str.substring(0,3);
//I wouldn't use substring , what if the address 191.0.0.1 ?
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
Because you are using React, the props value was faked with the function getFakePropValue. The code inside is irrelevant, what I am doing is returning a String randomly, in case you have allowed in your React Component for the prop to be empty. This is to show how you an create minimal robust code to avoid having exceptions.
Moving on, the following is a safety net to make sure the variable trial123 always has a string value, even if it's "".
let trial123 = getFakePropValue() || "";
That means that if the function returns something like null , the boolean expression will execute the second apart, and return an empty string "" and that will be the value for trial123.
Moving on, the line where you convert to toString I have removed, I assume you are already getting the value in string format. Next.
var strFirstThree = trial123.split('.');
That creates an array where each position holds a part of the IP addrss. So 19.0.0.1 would become [19,0,0,1] that's thanks to the split by the delimiter . . Next.
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
This last piece of code uses the conditional if to make sure that my array has values before I try to splice it and join. The conditional is not to avoid an exception, since splice and join on empty arrays just returns an empty string. It's rather for you to be able to raise an error or something if needed. So if the array has values, I keep the first two positions with splice(0,2) and then join that array with a '.'. I recommend it more than the substr method you were going for because what if you get a number that's 191.0.0.1 then the substr would return the wrong string back, but with splice and join that would never happen.
Things to improve
I would strongly suggest using more human comprehensible variables (reflect their use in the code)
The right path for prop value checking is through Prop.Types, super easy to use, very helpful.
Happy coding!

JS - What is the difference here?

I'm a newbie to JS and it would be extremely useful to know what the differenece is between the following two if statement conditions...
First condition (not actually working):
if ( window.location.pathname == '/#register' ) {
// Code
}
Second condition:
if (document.URL.indexOf("#register") >= 0) {
// Code...
}
FYI, this would help me solve a bug I'm experiencing here
The first checks for an exact match. And it does it on the pathname, which doesn't include the hash, so it probably doesn't do what you want.
The second one checks the string contains "#register", so the full path could be bigger, like /#register_or_not or /some/other/path#register
Probably your best option would be to do a regex pattern match on the URL, to ensure that the hash it matches is ONLY 'register', while allowing the rest of the URL to be whatever:
if (document.URL.match(/.*#register$/)) {
The second just check if the url contains #register, the first the url path, you can do it also with location.hash
if(location.hash=='#register') { //....
The first one performs an exact match between window.location.pathname and /#register. The second one looks for #register anywhere in document.URL.
This if block check the strings whether they are equal or not
if ( window.location.pathname == '/#register' ) {
// Code
}
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
if (document.URL.indexOf("#register") >= 0) {
// Code...
}

CodeMirror - Using RegEx with overlay

I can't seem to find an example of anyone using RegEx matches to create an overlay in CodeMirror. The Moustaches example matching one thing at a time seems simple enough, but in the API, it says that the RegEx match returns the array of matches and I can't figure out what to do with it in the context of the structure in the moustaches example.
I have a regular expression which finds all the elements I need to highlight: I've tested it and it works.
Should I be loading up the array outside of the token function and then matching each one? Or is there a way to work with the array?
The other issue is that I want to apply different styling depending on the (biz|cms) option in the regex - one for 'biz' and another for 'cms'. There will be others but I'm trying to keep it simple.
This is as far as I have got. The comments show my confusion.
CodeMirror.defineMode("tbs", function(config, parserConfig) {
var tbsOverlay = {
token: function(stream, state) {
tbsArray = match("^<(biz|cms).([a-zA-Z0-9.]*)(\s)?(\/)?>");
if (tbsArray != null) {
for (i = 0; i < tbsArray.length; i++) {
var result = tbsArray[i];
//Do I need to stream.match each element now to get hold of each bit of text?
//Or is there some way to identify and tag all the matches?
}
}
//Obviously this bit won't work either now - even with regex
while (stream.next() != null && !stream.match("<biz.", false)) {}
return null;
}
};
return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "text/html"), tbsOverlay);
});
It returns the array as produced by RegExp.exec or String.prototype.match (see for example https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/match), so you probably don't want to iterate through it, but rather pick out specific elements the correspond to groups in your regexp (if (result[1] == "biz") ...)
Look at implementation of Code Mirror method match() and you'll see, that it processes method parameter for two types: string and RegExp.
Your constant in
stream.match("<biz.")
is of string type.
Define it in RegExp type:
tbsArray = /<biz./g
Thus, your stream will be matched with RegExp.

Shorthand-if with character index check

I am using a shorthand if statement to check if content has an italic tag in it.
remove = (content.indexOf('<i>') === true) ? true : false;
alert("ORIGINAL CONTENT: " + content + "\nDoes content contain <i>? " + remove);
When that alert pops up, it shows the following:
Alert box shows < i > in string, but returns false
What am I doing wrong?
indexOf returns the position of the string inside another string, and -1 if it's not found. It's not like strpos in PHP. So you have to check content.indexOf('<i>') !== -1 instead.
In your case, I'd simply define
remove = content.indexOf('<i>') !== -1;
The ternary operator (I used to know that by this name) isn't really necessary here, as the comparison already gives the boolean value you need.
Mostly covered in other answers, but in:
> content.indexOf('<i>') === true
note that String.prototype.intexOf returns a Number and it is being compared to a Boolean. Since they are different Types, the result will always be false. If the equals operator "==" had been used, it would return true if the left hand expression returned any value other than zero (0).
Incidentally, italic text can be implemented using elements other than I, e.g. a span element with suitable styling applied through CSS.
Have you considered using Regex?
remove = /<i>/.test(content);
Thanks RobG for the correction.

Categories

Resources