Javascript - String contains commas and dashes - javascript

I have a quick question.
How do I check whether there are any commas or dashes in a string? Thx

/[,\-]/.test(yourString)
this returns true if yourString contains commas or dashes or false otherwise.

/(,|-)/.test(yourString); // returns true if there are commas or dashes in the string, false otherwise.

You can use the indexOf() method to check the presence of a substring inside a string. If the return value is greater or equal to 0 there is at least one occurrence of the substring :
var str1 = "my-string";
var str2 = "string, mine";
var str3 "simple";
str1.indexOf("-"); //returns 2
str2.indexOf(","); //returns 6
str3.indexOf("-"); //returns -1

Use
var n = str.indexOf("some. text, here");
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.

Just checking index of , or -
Example code:
var str="dhfdshf-43sf";
if(str.indexOf('-')!=-1){
//- exist
}
var str2="dhfdshf,43sf";
if(str.indexOf(',')!=-1){
// , exist
}

Related

Getting second digit in a string using Javascript + Regex?

I'm wondering how I can get the second digit of a string where we don't know the number of digits the second number will be and without using splice or substring.
Ex. Channel.0.This.13
Should Return: 13
I've seen a few similar questions but they
typically know the number of digits the second number will be or
use splicing and substring, which I do not want to use in this case.
I appreciate the help :)
You could use String.prototype.match
In case that the string does not have any number, which matches will return null, you should use optional chaining ?. for a safer array index access
const str = "Channel.0.This.13";
const res = str.match(/\d+/g)?.[1];
console.log(res);
Use this regex (\d*)$. This will return only group with numbers which in the end of the string.
try this:
^[^\d]*\d+[^\d]+(\d+).*
Example:
const secondDigit = "Channel.0.This.13".match(/^[^\d]*\d+[^\d]+(\d+).*/).pop();
console.log(Number(secondDigit)); // 13
Assuming the original string contains only alphabets, numbers and '.' (in between),
Here is my solution (Pseudo code):
String givenString;
regex=/([0-9]+)(\.[a-zA-Z]+)?(\.[0-9]+)/;
//below code will return an array or null (if no second number is present)
match=givenString.match(regex);
//access last element of array. It will be like '.13' , just remove '.' and you are good to go
match.pop()
Javascript Regex Docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges
String.prototype.match() returns an array whose contents depend on the presence or absence of the global (g) flag, or null
const input1 = "Channel.0.This.13",
input2 = "Channel.0.This",
input3 = "Channel.This.";
const digitMatch = function (input) {
const digits = input.match(/\d+/g);
return (digits && digits[1]) || "Not Found";
};
console.log(digitMatch(input1));
console.log(digitMatch(input2));
console.log(digitMatch(input3));
if no matches are found.
It will help .*?\d+.*?(\d+).*$
"Channel.0.This.13.Channel.0.This.56".match(/.*?\d+.*?(\d+).*$/).pop()
// Output: 13
"Channel.0.This.13".match(/.*?\d+.*?(\d+).*$/).pop()
// Output: 13
You can reference the regex .match() key. str.match(reg)[1]
const str1 = 'Channel.0.This.13'
const str2 = 'some.otherStrin8..'
const str3 = '65 people.For.&*=20.them,98'
const regex = /\d+/g
function matchSecond(str, reg) {
str.match(reg)[1] ? output = str.match(reg)[1] : output = false
return output;
}
console.log(matchSecond(str1,regex))
console.log(matchSecond(str2,regex))
console.log(matchSecond(str3,regex))

Regular expression match in javascript on a list of items

How to check in javascript if my string contains any of the characters ~ and ’.
Is there a way to achieve this using regular expression match test, rather than writing a for loop to check if my string contains any of there characters using indexOf()
regex.test(str); is the thing you want to check. It looks in str if it is mathing regex, true if it does, else false
var a = "hey";
var b = "h~y";
var c = "he’";
var reg = /[’~]/ ;
console.log(reg.test(a)); // false
console.log(reg.test(b)); // true
console.log(reg.test(c)) // true
Just try to find given string using indexOf() it will return value greater than -1. If value is 0,1 or any number then true else false.
var string = "Some Text'";
if (string.indexOf("~") > -1 || string.indexOf("'") > -1)
{
console.log("contains");
}else{
console.log("not contains");
}

indexOf has a result of true when comparing two unique strings

I'm expecting this to return false, as the first string is "pass / fail" and the string that is passed into IndexOf is "Numerical Specification".
Am I not understanding how this function works? I thought it checks if string A is contained within string B?
you probably meant to use "".contains, which returns an up/down boolean instead of a match index:
"abc".includes("b"); // == true;
"abc".includes("x"); // == false;
since -1 in js is "truthy", your indexOf() usage won't work as a conditional.
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.
For example:
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome"); //output 13
Similiaryly:
var str = "Hello world";
var n = str.indexOf("welcome"); //output -1

Parse strings with a regex and store the result in an array or a string

I need some help to improve my code :
I am beginner with regex system.
I would like to fecth NUMBER below in script and store it in a string or an array to moment that output "NUMBER1,NUMBER1_NUMBER2_,NUMBER2" I don't understand why, i would like jsut NUMBER at the end ;
function fetchnumber(){
extract = "";
for(picture = 1 ; picture < 5; picture++){
// get background image as a string as this :
// url('http://www.mywebsite.com/directory/image_NUMBER_.png');
var NumberOfPicture = document.getElementById(picture).style.backgroundImage ;
reg = /\_(.*)\_/;
extract += reg.exec(NumberOfPicture);
}
}
I write this small example for you. Hope this help you.
var inputString = 'http://www.mywebsite.com/directory/image_123_.png';
var imageNumber = (/image_([^_]+)_\.\w{3}$/.exec(inputString) || [,false])[1];
// so into imageNumber variable you will have a 123 or false if there is no mach
if (imageNumber) {
// here you can do something with finded
// part of text.
}
I wish you luck with the implementation.
You asked why there is [1] instead [0]. The explanation is that we need to have
the same behavior when there is no match of regex. This is quote from MDN
The exec() method executes a search for a match in a specified string.
Returns a result array, or null.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
So. If there is match for regular expression the returned array will consist
from matched string located at zero index ([0]) and with first backreference at first index [1] back references are symbols between brackets (sddsd). But if there is no match we will pass [,false] as output so we will expect the result
into first array index [1]. Try the code with different input. For example:
var inputString = 'some text some text ';
var imageNumber = (/image_([^_]+)_\.\w{3}$/.exec(inputString) || [,false])[1];
// so into imageNumber variable you will have a 123 or false if there is no mach
if (imageNumber) {
// here you can do something with finded
// part of text.
}
So .. In this case the condition will not be executed at all. I mean:
if (imageNumber) {
// here you can do something with finded
// part of text.
}

Efficiently getting string?

I want to take two values from string
"105.106"
The values 105 and 106 can be different the point(.) will decide their splitting after split i want these values in variable. i have look it into indexOf and split method but not getting logic.
It's quite simple:
var str = "105.106";
var values = str.split('.'); // (or "." or /\./)
console.log(values[0]); // Output: 105
console.log(values[1]); // Output: 106
Live demo.
You can learn more about how split works here. In short, split is a method on the String's prototype that you pass it the character that acts as a delimiter, and it tokenizes the string based on that character. For example, if you had "123,456,789" and you wanted to tokenize the string as if the , was the delimiter, you would get "123", "456", and "789".
Now your string is "105.106", and you want . to act as the delimiter, as such you write something similar to:
tokens = "105.106".split(".");
tokens[0] == "105"; // true
tokens[1] == "106"; // true
As you can see, split has decomposed the string into an array with two components, containing the string splited by the . character.
You can do:
var str = "105.106";
// does the string contain floating point dot ?
if (str.indexOf('.') >= 0) {
var values = str.split('.');
alert(values[0]); // value before dot
alert(values[1]); // value after dot
}
else {
alert(str); // string did not contain a dot/point
}
Above code will give you both values before and after dot/point in case it contains a dot else it will give you string as it was.
The JavaScript String.split(delimiter) method does what you want. Use it like this:
var s = "105.106";
var values = s.split(".");
// values[0] = "105", values[1] = "106".
I've not tested it but guess this may work
var str="xxx.xxxxx";
dot=str.lastIndexOf('.');
num2=str.substring(dot+1);
num1=str.substring(0,dot);

Categories

Resources