Javascript regular expression to check if the file ends with (.csv) - javascript

I want to select the last .csv in text.csv.csv
I tried (\.csv)$ but it didn't work.
I am using this site to test my regax
https://regex101.com/#javascript

Please try:
/\.csv$/
Added '\' to escape the dot.
You need to use a backslash to escape the dot character, to check if the dot is present.
If you don't escape it, the dot represents a single character, so, for example, 'test.csv.xxxcsv' would match too.
Working example

Why do you need regex for this?
Simple JavaScript functions should suffice
var str = "myFileName.csv";
var index = str.lastIndexOf(".csv");
var len = str.length;
var res = "";
if(len - index == 4)
{
res = "CSV Found"
}
else {
res = "CSV Not Found"
};

Related

Removing commas unless inside quotes, not using regexp

I am trying to remove commas in a string unless they appear inside quotes.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
mystring = mystring.split(',').join(newchar);// working correctly
document.write(mystring);
Output I have is
this is a test example "i dont know" jumps
Expected output
this is a test example "i, dont know" jumps
A couple of questions. How can I find the index of string so that inside the quotation it will include comma but outside of quotation " it will not include comma ,. I know I have to use indexOf and substring but I don't know how to format it? (No regex please as I'm new to JavaScript and I'm just focusing on the basics.)
Loop through the string, remembering whether or not you are inside a set of quotation marks, and building a new string to which the commas inside quotes are not added:
var inQuotes = false; // Are we inside quotes?
var result = ''; // New string we will build.
for (var i = 0; i < str.length; i++) { // Loop through string.
var chr = str[i]; // Extract character.
var isComma = chr === ','; // Is this a comma?
var isQuote = chr === '"'; // Is this a quote?
if (inQuotes || !isComma) { // Include this character?
if (isQuote) inQuotes = !inQuotes; // If quote, reverse quote status.
result += chr; // Add character to result.
}
}
This solution has the advantage compared to the accepted one that it will work properly even if the input has multiple quotes strings inside it.
This will work, but it's not ideal for all cases. Example: It will not work for a string with more than 2 quotation marks.
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
var firstIndex = mystring.indexOf("\"");
var lastIndex = mystring.lastIndexOf("\"");
var substring1 = mystring.substring(0,firstIndex).split(',').join(newchar);
var substring2 = mystring.substring(lastIndex).split(',').join(newchar);
mystring = substring1 + mystring.substring(firstIndex, lastIndex) + substring2;
document.write(mystring);
Some day you need to start using regexp, than regexr.com is your friend. The regexp solution is simple:
var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '_';
mystring = mystring.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g).join(newchar);// working correctly
document.write(mystring);

Retrieving several capturing groups recursively with RegExp

I have a string with this format:
#someID#tn#company#somethingNew#classing#somethingElse#With
There might be unlimited #-separated words, but definitely the whole string begins with #
I have written the following regexp, though it matches it, but I cannot get each #-separated word, and what I get is the last recursion and the first (as well as the whole string). How can I get an array of every word in an element separately?
(?:^\#\w*)(?:(\#\w*)+) //I know I have ruled out second capturing group with ?: , though doesn't make much difference.
And here is my Javascript code:
var reg = /(?:^\#\w*)(?:(\#\w*)+)/g;
var x = null;
while(x = reg.exec("#someID#tn#company#somethingNew#classing#somethingElse#With"))
{
console.log(x);
}
And here is the result (Firebug, console):
["#someID#tn#company#somet...sing#somethingElse#With", "#With"]
0
"#someID#tn#company#somet...sing#somethingElse#With"
1
"#With"
index
0
input
"#someID#tn#company#somet...sing#somethingElse#With"
EDIT :
I want an output like this with regular expression if possible:
["#someID", "#tn", #company", "#somethingNew", "#classing", "#somethingElse", "#With"]
NOTE that I want a RegExp solution. I know about String.split() and String operations.
You can use:
var s = '#someID#tn#company#somethingNew#classing#somethingElse#With'
if (s.substr(0, 1) == "#")
tok = s.substr(1).split('#');
//=> ["someID", "tn", "company", "somethingNew", "classing", "somethingElse", "With"]
You could try this regex also,
((?:#|#)\w+)
DEMO
Explanation:
() Capturing groups. Anything inside this capturing group would be captured.
(?:) It just matches the strings but won't capture anything.
#|# Literal # or # symbol.
\w+ Followed by one or more word characters.
OR
> "#someID#tn#company#somethingNew#classing#somethingElse#With".split(/\b(?=#|#)/g);
[ '#someID',
'#tn',
'#company',
'#somethingNew',
'#classing',
'#somethingElse',
'#With' ]
It will be easier without regExp:
var str = "#someID#tn#company#somethingNew#classing#somethingElse#With";
var strSplit = str.split("#");
for(var i = 1; i < strSplit.length; i++) {
strSplit[i] = "#" + strSplit[i];
}
console.log(strSplit);
// ["#someID", "#tn", "#company", "#somethingNew", "#classing", "#somethingElse", "#With"]

Get all words starting with X and ending with Y

I have got a textarea with keyup=validate()
I need a javascript function that gets all words starting with # and ending with a character that is not A-Za-z0-9
For example:
This is a text #user1 this is more text #user2. And this is even more #user3!
The function gives an array:
Array("#user1","#user2","#user3");
I am sure there must be a way to do this written on somewhere on the internet if I just google something but I have no idea what I have to look for.. I am very new with regular expresions.
Thank you very much!
The regular expression you want is:
/#[a-z\d]+/ig
This matches # followed by a sequence of letters and numbers. The i modifier makes it case-insensitive, so you don't have to put A-Z in the character class, and g makes it find all the matches.
var str = "This is a text #user1 this is more text #user2. And this is even more #user3!";
var matches = str.match(/#[a-z\d]+/ig);
console.log(matches);
JS
var str = "This is a text #user1 this is more text #user2. And this is even more #user3!",
var textArr = str.split(" ");
for(var i = 0; i < textArr.length; i++) {
var test = textArr[i];
matches = test.match(/^#.*.[A-Za-z0-9]$/);
console.log(matches);
};
Explanation:
You should also read about the regex(http://www.w3schools.com/jsref/jsref_obj_regexp.asp) and match(http://www.w3schools.com/jsref/jsref_match.asp) to get an idea how it works.
Basically, applying ^# means starting the regex look for #. $ means ending with. and .* any character in between.
To Test: http://www.regular-expressions.info/javascriptexample.html
Thanks for the replies above, they've helped me - Where I've written this method that hopefully answers the question about having a start and end regex check.
In this example it looks for ##_ at the start and _## at the end
e.g. ##_ anyTokenYouNeedToFind _##.
Code:
const tokenSearchHelper = (inputText) => {
let matches = inputText.match(/##_[a-zA-Z0-9_\d]+_##/ig);
return matches;
}
const out = tokenSearchHelper("Hello ##_World_##");
console.log(out);

Javascript replace all "%20" with a space

Is there a way to replace every "%20" with a space using JavaScript. I know how to replace a single "%20" with a space but how do I replace all of them?
var str = "Passwords%20do%20not%20match";
var replaced = str.replace("%20", " "); // "Passwords do%20not%20match"
Check this out:
How to replace all occurrences of a string in JavaScript?
Short answer:
str.replace(/%20/g, " ");
EDIT:
In this case you could also do the following:
decodeURI(str)
The percentage % sign followed by two hexadecimal numbers (UTF-8 character representation) typically denotes a string which has been encoded to be part of a URI. This ensures that characters that would otherwise have special meaning don't interfere. In your case %20 is immediately recognisable as a whitespace character - while not really having any meaning in a URI it is encoded in order to avoid breaking the string into multiple "parts".
Don't get me wrong, regex is the bomb! However any web technology worth caring about will already have tools available in it's library to handle standards like this for you. Why re-invent the wheel...?
var str = 'xPasswords%20do%20not%20match';
console.log( decodeURI(str) ); // "xPasswords do not match"
Javascript has both decodeURI and decodeURIComponent which differ slightly in respect to their encodeURI and encodeURIComponent counterparts - you should familiarise yourself with the documentation.
Use the global flag in regexp:
var replaced = str.replace(/%20/g, " ");
^
using unescape(stringValue)
var str = "Passwords%20do%20not%20match%21";
document.write(unescape(str))
//Output
Passwords do not match!
use decodeURI(stringValue)
var str = "Passwords%20do%20not%20match%21";
document.write(decodeURI(str))
Space = %20
? = %3F
! = %21
# = %23
...etc
This method uses the decodeURIComponent() (See edit below) method, which is the best one.
var str = "Passwords%20do%20not%20match%21";
alert(decodeURIComponent(str))
Here it how it works:
Space = %20
? = %3F
! = %21
# = %23
...etc
There's a good example of that at the Mozilla docs [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI]
Edit: decodeURIComponent works better, look at the example.
If you want to use jQuery you can use .replaceAll()
If you need to remove white spaces at the end then here is a solution:
https://www.geeksforgeeks.org/urlify-given-string-replace-spaces/
const stringQ1 = (string)=>{
//remove white space at the end
const arrString = string.split("")
for(let i = arrString.length -1 ; i>=0 ; i--){
let char = arrString[i];
if(char.indexOf(" ") >=0){
arrString.splice(i,1)
}else{
break;
}
}
let start =0;
let end = arrString.length -1;
//add %20
while(start < end){
if(arrString[start].indexOf(' ') >=0){
arrString[start] ="%20"
}
start++;
}
return arrString.join('');
}
console.log(stringQ1("Mr John Smith "))

Remove special character from the starting of a string and search # symbol.in javascript

I want to remove special characters from the starting of the string only.
i.e, if my string is like {abc#xyz.com then I want to remove the { from the starting. The string shoould look like abc#xyz.com
But if my string is like abc{#xyz.com then I want to retain the same string as it is ie., abc{#xyz.com.
Also I want to check that if my string has # symbol present or not. If it is present then OK else show a message.
The following demonstrates what you specified (or it's close):
var pat = /^[^a-z0-9]*([a-z0-9].*?#.*?$)/i; //pattern for optional non-alphabetic start followed by alphabetic, followed by '#' somewhere
var testString = "{abc#xyz.com"; //Try with {abcxyz.com for alert
arr = pat.exec(testString);
var adjustedString;
if (arr != null) { adjustedString = arr[1]; } //The potentially adjustedString (chopped off non-alphabetic start) will be in capture group 1
else { adjustedString = ""; alert(testString + " does not conform to pattern"); }
adjustedString;
I have used two separate regex objects to achieve what you require .It checks for both the conditions in the string.I know its not very efficient but it will serve your purpose.
var regex = new RegExp(/(^{)/);
var regex1 = new RegExp(/(^[^#]*$)/);
var str = "abc#gmail.com";
if(!regex1.test(str)){
if(regex.test(str))
alert("Bracket found at the beginning")
else
alert("Bracket not found at the beginning")
}
else{
alert("doesnt contain #");
}
Hope this helps

Categories