Error in checking if a string only contains digits - node.js

let duration = "365460‬"
console.log((/^\d+$/.test(duration)))
Actual result: false
Expected result: true
But,
let duration = "11"
console.log((/^\d+$/.test(duration)))
Actual result: true
Expected result: true
What could be the problem? Please guide me

There's an extra character after 365460‬, and that's why your pattern does not match!
You can use the following to diagnose such issues in the future:
const duration = "365460‬";
for(let i = 0; i < duration.length; ++i) {
console.log(`Char at index ${i}: ${duration[i]} | Unicode: ${duration.charCodeAt(i)}`);
}
As you may observe from the result of the above code, there is a character with unicode value 8236, which is some sort of formatting character known as "Pop Directional Formatting".
https://www.codetable.net/decimal/8236

There is a unicode character at the end of the string which makes result false.
duration = "365460‬"
console.log(duration.split(""));
console.log(duration.length); // 7 instead of 6

isdigit(str) {
let pattern = /^\d+$/
if (str.match(pattern)) {
return true
} else {
return false
}
}
You can use the above function it solves the problem of detecting only numbers.

You can use isNaN() instead which would be the relevant syntax in your case

Related

Making sure every Alphabet is in a string (Kotlin)

So I have a question where I am checking if a string has every letter of the alphabet in it. I was able to check if there is alphabet in the string, but I'm not sure how to check if there is EVERY alphabet in said string. Here's the code
fun isPangram (pangram: Array<String>) : String {
var panString : String
var outcome = ""
for (i in pangram.indices){
panString = pangram[i]
if (panString.matches(".^*[a-z].*".toRegex())){
outcome = outcome.plus('1')
}
else {outcome = outcome.plus('0')}
}
return outcome
}
Any ideas are welcomed Thanks.
I think it would be easier to check if all members of the alphabet range are in each string than to use Regex:
fun isPangram(pangram: Array<String>): String =
pangram.joinToString("") { inputString ->
when {
('a'..'z').all { it in inputString.lowercase() } -> "1"
else -> "0"
}
}
Hi this is how you can make with regular expression
Kotlin Syntax
fun isStrinfContainsAllAlphabeta( input: String) {
return input.lowercase()
.replace("[^a-z]".toRegex(), "")
.replace("(.)(?=.*\\1)".toRegex(), "")
.length == 26;
}
In java:
public static boolean isStrinfContainsAllAlphabeta(String input) {
return input.toLowerCase()
.replace("[^a-z]", "")
.replace("(.)(?=.*\\1)", "")
.length() == 26;
}
the function takes only one string. The first "replaceAll" removes all the non-alphabet characters, The second one removes the duplicated character, then you check how many characters remained.
Just to bounce off Tenfour04's solution, if you write two functions (one for the pangram check, one for processing the array) I feel like you can make it a little more readable, since they're really two separate tasks. (This is partly an excuse to show you some Kotlin tricks!)
val String.isPangram get() = ('a'..'z').all { this.contains(it, ignoreCase = true) }
fun checkPangrams(strings: Array<String>) =
strings.joinToString("") { if (it.isPangram) "1" else "0" }
You could use an extension function instead of an extension property (so it.isPangram()), or just a plain function with a parameter (isPangram(it)), but you can write stuff that almost reads like English, if you want!

Find ksh functions using nodejs regex

I want to write some regex which matches the following: any char regargless how often and then and opening and closing bracket. Also I don't want it to match if there is a # infront of it.
Here is what I tried so far:
\s*^(?!#)*[A-Za-z0-9_]*\(\)
The problem is that this regex seems to match every line in the test file, not just the functions that I want.
Have a great day
EDIT:
function match(array, regex) {//Rematcher
back = [];
for (let i = 0; i < array.length; i++) {
let line = array[i];
if (regex.test(line)) {
back.push(line);
}
}
return back
}
function find(text) {//function finder
let reg = new RegExp("^(?!#)*\w*\(\)");
return reMatcher.match(text, reg);
}
let content = fs.readFileSync(file, "UTF-8");//starting point
let functions = find_functions.find(content);
content = content.split("\n");
//Testfile
meldet()
{
if true
then
if true
then
echo Pseudocode
fi
echo Pseudocode
fi
}
The regex should only match the first line, but instead it matches every line and also it shouldn't match on lines where a # is before the function header
In the pattern \s*^(?!#)*[A-Za-z0-9_]*\(\) you can omit the \s* before the start of the line anchors.
As you don't match a # in the character class, you can also omit the negative lookahead (?!#)
Instead of using reMatcher.match(text, reg);, you could use match on the text variable.
Note to double escape the backslashes in the RegExp constructor.
You could update the function find to:
function find(text) {
let reg = new RegExp("\\s*^(?!#)*[A-Za-z0-9_]*\\(\\)");
return text.match(reg)[0]; // Or first check the value before indexing
}

Remove nth character from string

I have seen many methods for removing the last character from a string. Is there however a way to remove any old character based on its index?
Here is a safe Swift 4 implementation.
var s = "Hello, I must be going"
var n = 5
if let index = s.index(s.startIndex, offsetBy: n, limitedBy: s.endIndex) {
s.remove(at: index)
print(s) // prints "Hello I must be going"
} else {
print("\(n) is out of range")
}
While string indices aren't random-access and aren't numbers, you can advance them by a number in order to access the nth character:
var s = "Hello, I must be going"
s.removeAtIndex(advance(s.startIndex, 5))
println(s) // prints "Hello I must be going"
Of course, you should always check the string is at least 5 in length before doing this!
edit: as #MartinR points out, you can use the with-end-index version of advance to avoid the risk of running past the end:
let index = advance(s.startIndex, 5, s.endIndex)
if index != s.endIndex { s.removeAtIndex(index) }
As ever, optionals are your friend:
// find returns index of first match,
// as an optional with nil for no match
if let idx = s.characters.index(of:",") {
// this will only be executed if non-nil,
// idx will be the unwrapped result of find
s.removeAtIndex(idx)
}
Swift 3.2
let str = "hello"
let position = 2
let subStr = str.prefix(upTo: str.index(str.startIndex, offsetBy: position)) + str.suffix(from: str.index(str.startIndex, offsetBy: (position + 1)))
print(subStr)
"helo"
var hello = "hello world!"
Let's say we want to remove the "w". (It's at the 6th index position.)
First: Create an Index for that position. (I'm making the return type Index explicit; it's not required).
let index:Index = hello.startIndex.advancedBy(6)
Second: Call removeAtIndex() and pass it our just-made index. (Notice it returns the character in question)
let choppedChar:Character = hello.removeAtIndex(index)
print(hello) // prints hello orld!
print(choppedChar) // prints w

String Comparison Not working Arduino

Could somebody explain what is wrong with this code. WHY is the if statement always false when it is matching the exact strings..I have tried it with == as well..Still, every time I am getting No Match Found !!.
String inData = "";
char inChar;
String property;
String a = "test";
void loop() {
Serial.println("String Comparison");
if(Serial.available() > 0){
while(Serial.available()>0) {
inChar = Serial.read();
inData.concat(inChar);
}
//Extracting Property
property = inData.substring(inData.lastIndexOf(":")+2); // Extracts the String "test"
Serial.println("Property:" +property);
if(property.equals(a)){ // It never matches though, it is TRUE all the time
Serial.println(" Matched !! ");
}
else
Serial.println(" Match Not Found !! ");
inData = "";
}
delay(5000);
}
Since I am able to see matches match and misses miss I think I need more information to replicate the error.
Since I don't see it happening I would guess it has to do with whatever the input is and how this line parses it.
property = inData.substring(inData.lastIndexOf(":")+2); // Extracts the String "test"
What is the current input that is failing?
Can you include your printed output with that input?
Add a line to print out property.length() to test for hidden whitespace characters

Comparing sentences (strings) in AS3

I'm building a short quiz where the user needs to input the meaning of an acronym.
This means I need to compare a long string (usually a sentence) typed in by the user with an acronym.
I have a feeling I'm not doing it right. For my testing I'm copy-pasting the correct answer to make sure the spelling is correct however I keep getting the feedback that the answer is incorrect.
My question is, am I comparing correctly?
Here's my code:
var arrQuestions:Array = [["LOL","Laughing Out Loud"], ["OMG", "Oh My God"], ["BTW", "By The Way"]];
var i:Number=0;
function setup():void {
quiztext_txt.text = arrQuestions[i][0];
trace(quiztext_txt.text);
trace(arrQuestions[i][1]);
check_btn.addEventListener(MouseEvent.CLICK, clickHandler);
}//End of Setup()
setup();
function clickHandler(event:MouseEvent):void {
var givenString:String;
var inputString:String;
inputString = userinput_txt.text;
givenString = arrQuestions[i][1];
if (inputString == givenString) {
feedback_txt.text = "Correct!";
} else {
feedback_txt.text = "Wrong!";
}
}
Is there any whitespace before/after the user input? Is the value of i changing in between?
else
{
//what does it trace?
trace("given answer: " + inputString + "\ncorrect answer: " + givenString);
feedback_txt.text = "Wrong!";
}
try clearing the text field in your setup function like so:
function setup():void
{
userinput_txt.text = "";
quiztext_txt.text = arrQuestions[i][0];
trace(quiztext_txt.text);
trace(arrQuestions[i][1]);
check_btn.addEventListener(MouseEvent.CLICK, clickHandler);
}//End of Setup()
For any kind of string matching I would strongly recommend looking into regular expressions (RegExp). In the regular expression written below I am matching each word, then I say [ ]+ which means "at least one or more spaces", then at the end of the expression I use /gi to say that the expression is case insensitive. In the code above if I type the phrase in lowercase its not going to match, a quick fix for this would be to use this if(inputString.toLowerCase() == givenString.toLowerCase()) which would catch this. Heres the regexp example:
// testString could easily equal myTextField.text
var testString:String = "lauGHing OuT loUD";
// you could store each one in an array, as you were before
var regEx:RegExp = /laughing[ ]+out[ ]+loud/gi
trace( regEx.test( testString ) ); //returns true,test() returns a Boolean
Hope this helps.

Resources