Can I chain a substring check in javascript? - javascript

I am using the following code:
if (store.getItem('TopicID') != "00")
TopidID is always 4 digits and what I need to do is change this to check if the last two digits are "00".
Can I do this as part of the above by just adding ".substring(from, to)" or do I need to put this into a variable and then check the variable?

Use if (!/00$/.test(store.getItem('TopicID')) to check for the last 2 digits not forming '00'. That way the length of the value of store.getItem('TopicID') doesn't matter, you always check for the last two characters of the value, and you don't need the substring 'chaining'.
By the way, I supposed store.getItem('TopicID') returns a String here.
To be complete and in response to Paul Phillips comment: in !/00$/.test([somestring]), /00$/ is a Regular Expression, a special text string for describing a search pattern. In this case it means: for the string resulting from store.getItem('TopicID'), check if you can find 2 consecutive zero's, where the $-sign means 'check for that pattern at the end of the string'.
To be even more complete on the subject of 'chaining': as long as a method is contained by the object to chain, everything can be chained. A completely nonsensical example of that:
Number(/00$/.test('0231')) //convert a boolean to a Number
.toFixed(2) //a Number has the toFixed method
.split('.')[1] //toFixed returns a String, which has method split
.substr(1) //the second element is a string, so substr applies
.concat(' world') //still a string, so concat will do
.split(' ') //string, so split works
.join(' hello ') //from split an array emerged, so join applies
;
//=> result of this chain: '0 hello world'

Can I do this as part of the above by just adding ".substring(from, to)"
Yes, you can. You got the wrong syntax, though.
if (store.getItem('TopicID').substring( 2 ) != "00")

Chaining it would work. So would extracting a local variable. So no, you don't need to. Do it if you think it makes the code more readable.

you can do using slice too
if (store.getItem('TopicID').slice(2,4) != "00") {
// Do Your Stuff
}

Try to use substr or substring with negative start:
if ( store.getItem('TopicID').substr(-2) !== "00" ){...}
or
if ( store.getItem('TopicID').substring(-2) !== "00" ){...}

if it's four digits, you can use
if (store.getItem('TopicID') % 100)

var yourString = (store.getItem('TopicID'))
if(yourString.substring((yourString.length - 2), 2) == "00")
The code above doesn't care how long your string is. It gets the last two digits and compare to "00"

Related

What value does a substring have if it doesn't exist?

I have a string, msg. I want to check if the third character in the string exists or not.
I've tried if (msg.substring(3, 4) == undefined) { ... } but this doesn't work. What would the substring be equal to if it does not exist?
The third character of the string exists if the string has three characters, so the check you are looking for is
msg.length >= 3
As to your question about a non-existent substring, you get the empty string, which you can test in a console:
> "dog".substring(8, 13)
''
It's generally worth a mention that indexing and taking the length of characters is fraught with Unicode-related difficulties, because what JavaScript thinks of as a character is not really a character, but a UTF-16 character code. So watch out for:
> "πŸ˜¬πŸ€”".length
4
> "πŸ˜¬πŸ€”"[1]
'οΏ½'
> "πŸ˜¬πŸ€”"[2]
'οΏ½'
> [..."πŸ˜¬πŸ€”"][1]
'πŸ€”'
So if you are looking for better characters do:
[...msg].length >= 3
That will still not work with Unicode grapheme clusters, but it is at least better than taking the actual length of string, which is broken in JavaScript (unless you are dealing with what they call BMP characters).
From the documentation:
Any argument value that is less than 0 or greater than stringName.length is treated as if it were 0 and stringName.length, respectively.
This isn't super intuitive but your example will be an empty string "" (or if the first position has a character and you've added a larger gap, it will be a string that is shorter than the space between indexStart and indexEnd:
const str = 'hi';
console.log(str.substring(1, 4)); // is "i"
You could take a standard property accessor for getting a character or undefined.
const
string0 = '',
string1 = 'a',
string2 = 'ab',
string3 = 'abc',
string4 = 'abcd';
console.log(string0[2]); // undefined
console.log(string1[2]); // undefined
console.log(string2[2]); // undefined
console.log(string3[2]); // c
console.log(string4[2]); // c
If string doesn't contains enough letters substrings doesn't returns nothing. You can try use string as array which return undefined if index doesn't exist.
if ( msg[2] !== undefined ) {}

Remove certain re-occurring characters from a string

I am quite new to JS and i have a problem:
I am trying to compare a string (as integer) with an input (as integer). The problem occurs because, the string is written as 10'000'000 for e.g. and the integer as 10000000, with 4 possible scenarios:
- 1'000'000
- 10'000'000
- 100'000'000
- 1'000'000'000
That is, the number (as string) can be from 1 million to 1 billion.
I want to erase (or replace with "") all of my " ' " characters so that the format which i will get for the string will be the same as the one of the integer
E.g. Integer: 95500000 String: 95'500'000 ---> need it to be 95500000
A similar solution but not quite the same is provided here:
Regex remove repeated characters from a string by javascript
String: 95'500'000 ---> need it to be 95500000
That’s as simple as "95'500'000".replace(/'/g, '')
g modifier makes it replace all occurrences, and not just the first one.
const str = "9'0'0000"
const removedSlashStr = str.split('').reduce((removedSlash, char) => {
if(char !== "'") removedSlash+=char
return removedSlash
}, '')
console.log(removedSlashStr) // "900000"

Extract specific chars from a string using a regex

I need to split an email address and take out the first character and the first character after the '#'
I can do this as follows:
'bar#foo'.split('#').map(function(a){ return a.charAt(0); }).join('')
--> bf
Now I was wondering if it can be done using a regex match, something like this
'bar#foo'.match(/^(\w).*?#(\w)/).join('')
--> bar#fbf
Not really what I want, but I'm sure I miss something here! Any suggestions ?
Why use a regex for this? just use indexOf to get the char at any given position:
var addr = 'foo#bar';
console.log(addr[0], addr[addr.indexOf('#')+1])
To ensure your code works on all browsers, you might want to use charAt instead of []:
console.log(addr.charAt(0), addr.charAt(addr.indexOf('#')+1));
Either way, It'll work just fine, and This is undeniably the fastest approach
If you are going to persist, and choose a regex, then you should realize that the match method returns an array containing 3 strings, in your case:
/^(\w).*?#(\w)/
["the whole match",//start of string + first char + .*?# + first string after #
"groupw 1 \w",//first char
"group 2 \w"//first char after #
]
So addr.match(/^(\w).*?#(\w)/).slice(1).join('') is probably what you want.
If I understand correctly, you are quite close. Just don't join everything returned by match because the first element is the entire matched string.
'bar#foo'.match(/^(\w).*?#(\w)/).splice(1).join('')
--> bf
Using regex:
matched="",
'abc#xyz'.replace(/(?:^|#)(\w)/g, function($0, $1) { matched += $1; return $0; });
console.log(matched);
// ax
The regex match function returns an array of all matches, where the first one is the 'full text' of the match, followed by every sub-group. In your case, it returns this:
bar#f
b
f
To get rid of the first item (the full match), use slice:
'bar#foo'.match(/^(\w).*?#(\w)/).slice(1).join('\r')
Use String.prototype.replace with regular expression:
'bar#foo'.replace(/^(\w).*#(\w).*$/, '$1$2'); // "bf"
Or using RegEx
^([a-zA-Z0-9])[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#([a-zA-Z0-9-])[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$
Fiddle

Regular expression to match 0 or 1

I need a regexp to match either 0 or 1 entered into a field and no other characters at all, neither numeric nor alphas. How can I do it?
Single character, 0 or 1:
/^[01]$/
Multiple 0s or 1s (any order, no other characters):
/^[01]+$/g
Demo (Just add a + for the second example. The gm at the end in the demo is just for the example because there are multiple lines for test cases)
A simple 0|1 expression should work.
([01])
http://rubular.com/r/TMu6vsx6Dn
If you only want the first occurrence, this will work as well.
(^[01])
http://rubular.com/r/i3brvRutCg
Try this regex: /^(0|1)$/
Example:
/^(0|1)$/.test(0); // true
/^(0|1)$/.test(1); // true
/^(0|1)$/.test(2); // false
/^(0|1)$/.test(1001) // false
I would suggest simple string evaluation here since you have only two known acceptable values in the input string:
var input; // Your input string assume it is populated elsewhere
if (input === '0' || input === '1') {
// Pass
}
Note the use of strict string comparison here to eliminate matches with truthy/falsey values.
If you are really hell-bent on a regex, try:
/^[01]$/
The key here is the beginning ^ and ending $ anchors.

Is there a way to do a substring in Javascript but use string characters as the parameters for what you want to select?

So a substring can take two parameters, the index to start at and the index to stop at like so
var str="Hello beautiful world!";
document.write(str.substring(3,7));
but is there a way to designate the start and stopping points as a set of characters to grab, so instead of the starting point being 3 I would want it to be "lo" and instead of the end point being 7 I would want it to be "wo" so I would be grabbing "lo beautiful wo". Is there a Javascript function that serves that purpose already?
Sounds like you want to use regular expressions and string.match() instead:
var str="Hello beautiful world!";
document.write(str.match(/lo.*wo/)[0]); // document.write("lo beautiful wo");
Note, match() returns an array of matches, which might be null if there is no match. So you should include a null check.
If you're not familiar with regexes, this is a pretty good source:
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
use the method indexOf: document.write(str.substring(3,str.indexOf('wo')+2));
Yup, you can do this easily with regular expressions:
var substr = /lo.+wo/.exec( 'Hello beautiful world!' )[0];
console.log( substr ); //=> 'lo beautiful wo'
Use a regex brother:
if (/(lo.+wo)/.test("Hello beautiful world!")) {
document.write(RegExp.$1);
}
You need a backup plan in case the string does not match. Hence the use of test.
Regular expression may be able to achieve this to some extent, but there are many details that you must be aware of.
For example, if you want to find all the substrings that starts with "lo", and ends with the nearest "wo" after "lo". (If there are more than 1 match, the subsequent matches will pick up the first "lo" after the "wo" of last match).
"Hello beautiful world!".match(/lo.*?wo/g);
Using the RegExp constructor, you can make it more flexible (you can substitute "lo" and "wo" with the actual string you want to find):
"Hello beautiful world!".match(new RegExp("lo" + ".*?" + "wo", "g"));
Important: The downside of the RegExp approach above is that, you need to know what characters are special to escape them - otherwise, they will not match the actual substring you want to find.
It can also be achieve with indexOf, albeit a little bit dirty. For the first substring:
var startIndex = str.indexOf(startString);
var endIndex = str.indexOf(endString, startIndex);
if (startIndex >= 0 && endIndex >= 0)
str.substring(startIndex, endIndex + endString.length)
If you want to find the substring that starts with the first "lo" and ends with the last "wo" in the string, you can use indexOf and lastIndexOf to find it (with a small modification to the code above). RegExp can also do it, by changing .*? to .* in the two example above (there will be at most 1 match, so the "g" flag at the end is redundant).

Categories

Resources