Regex matching dates in a string in Javascript - javascript

Following up from this thread, im trying to make this work
JavaScript regular expression to match X digits only
string = '2016-2022'
re = /\d{4}/g
result = [...string.matchAll(re)]
This returns an array of two arrays. Is there a way to consolidate this into 1 array?
However it doesn't look like this is returning the desired results
I'm new to regular expression. What am I doing wrong?

this return an array of matches
result = string.match(re)

This is a function to parse the string encoding those two year values and return the inner years as items of an array:
let o = parseYearsInterval('2016-2022');
console.log(o);
function parseYearsInterval(encodedValue){
var myregexp = /(\d{4})-(\d{4})/;
var match = myregexp.exec(encodedValue);
if (match != null) {
let d1 = match[1];
let d2 = match[2];
//return `[${d1}, ${d2}]`;
let result = [];
result.push(d1);
result.push(d2);
return result;
} else {
return "not valid input";
}
}
I think there are better ways to do that like splitting the string against the "-" separator and return that value as is like:
console.log ( "2016-2022".split('-') )

Just do a split if you know that only years are in the string and the strucutre isn't changing:
let arr = str.split("-");

Question
string = '2016-2022'
re = /\d{4}/g
result = [...string.matchAll(re)]
This returns an array of two arrays. Is there a way to consolidate
this into 1 array?
Solution
You may simply flat the result of matchAll.
let string = '2016-2022'
let re = /\d{4}/g
console.log([...string.matchAll(re)].flat())
Alternative
If your structure is given like "yyyy-yyyy-yyyy" you might consider a simple split
console.log('2016-2022'.split('-'))

var str = '2016-2022';
var result = [];
str.replace(/\d{4}/g, function(match, i, original) {
result.push(match);
return '';
});
console.log(result);
I also wanted to mention, that matchAll does basicly nothing else then an while exec, that's why you get 2 arrays, you can do it by yourself in a while loop and just save back what you need
var result = [];
var matches;
var regexp = /\d{4}/g;
while (matches = regexp.exec('2016-2022')) result.push(matches[0]);
console.log(result);

Related

How to get the string just before specific character in JavaScript?

I have couple of strings like this:
Mar18L7
Oct13H0L7
I need to grab the string like:
Mar18
Oct13H0
Could any one please help on this using JavaScript? How can I split the string at the particular character?
Many Thanks in advance.
For var str = 'Mar18L7';
Try any of these:
str.substr(0, str.indexOf('L7'));
str.split('L7')[0]
str.slice(0, str.indexOf('L7'))
str.replace('L7', '')
Based on input that is given it I have created following function which can take n string in array and return the output in the format you have given. Check if this helps and if some use case is missed.
function generateStr(arr, splitStr) {
const processedStr = arr.map(value => value.split(splitStr)[0]);
return processedStr.join(" OR ");
}
console.log(generateStr(["Mar18L7", "Oct13H0L7"], "L7"));
You can use a regex like this
var data = ["Mar18L7", "Oct13H0L7"];
var regex = /^([a-zA-Z0-9]+)\L[a-zA-Z0-9]+$/;
var output = []
data.forEach(function(el){
var matches = el.match(regex);
output.push(matches[1]);
});
output variable will be equal to ['Mar18', 'Oct13H0'] and you can join all value usin the .join method on output array
var chain = output.join(" OR ");
// chain will be equal to "Mar18 OR Oct13H0"

String cutting with Javascript

I have a string like "home/back/step" new string must be like "home/back".
In other words, I have to remove the last word with '/'. Initial string always has a different length, but the format is the same "word1/word2/word3/word4/word5...."
var x = "home/back/step";
var splitted = x.split("/");
splitted.pop();
var str = splitted.join("/");
console.log(str);
Take the string and split using ("/"), then remove the last element of array and re-join with ("/")
Use substr and remove everything after the last /
let str = "home/back/step";
let result = str.substr(0, str.lastIndexOf("/"));
console.log(result);
You could use arrays to remove the last word
const text = 'home/back/step';
const removeLastWord = s =>{
let a = s.split('/');
a.pop();
return a.join('/');
}
console.log(removeLastWord(text));
Seems I got a solution
var s = "your/string/fft";
var withoutLastChunk = s.slice(0, s.lastIndexOf("/"));
console.log(withoutLastChunk)
You can turn a string in javascript into an array of values using the split() function. (pass it the value you want to split on)
var inputString = 'home/back/step'
var arrayOfValues = inputString.split('/');
Once you have an array, you can remove the final value using pop()
arrayOfValues.pop()
You can convert an array back to a string with the join function (pass it the character to place in between your values)
return arrayOfValues.join('/')
The final function would look like:
function cutString(inputString) {
var arrayOfValues = inputString.split('/')
arrayOfValues.pop()
return arrayOfValues.join('/')
}
console.log(cutString('home/back/step'))
You can split the string on the '/', remove the last element with pop() and then join again the elements with '/'.
Something like:
str.split('/');
str.pop();
str.join('/');
Where str is the variable with your text.

how to remove array String substring() Method using javascript?

I would like to know how can I remove the First word in the string using JavaScript?
For example, the string is "mod1"
I want to remove mod..I need to display 1
var $checked = $('.dd-list').find('.ModuleUserViews:checked');
var modulesIDS = [];
$checked.each(function (index) { modulesIDS.push($(this).attr("id")); })
You can just use the substring method. The following will give the last character of the string.
var id = "mod1"
var result = id.substring(id.length - 1, id.length);
console.log(result)
Try this.
var arr = ["mod1"];
var replaced= $.map( arr, function( a ) {
return a.replace("mod", "");
});
console.log(replaced);
If you want to remove all letters and keep only the numbers in the string, you can use a regex match.
var str = "mod125lol";
var nums = str.match(/\d/g).join('');
console.log(nums);
// "125"
If you don't want to split the string (faster, less memory consumed), you can use indexOf() with substr():
var id = "mod1"
var result = id.substr(id.indexOf(" ") -0);
console.log(result)

remove chars in String javascript Regex

I have a chain like this of get page
file.php?Valor1=one&Valor2=two&Valor3=three
I would like to be able to delete the get request parameter with only having the value of it. for example , remove two
Result
file.php?Valor1=one&Valor3=three
Try with
stringvalue.replace(new RegExp(value+"[(&||\s)]"),'');
Here's a regular expression that matches an ampersand (&), followed by a series of characters that are not equals signs ([^=]+), an equals sign (=), the literal value two and either the next ampersand or the end of line (&|$):
/&[^=]+=two(&|$)/
let input = 'file.php?&Valor1=one&Valor2=two&Valor3=three';
let output = input.replace(/&[^=]+=two/, '');
console.log(output);
If you're getting the value to be removed from a variable:
let two = 'two';
let re = RegExp('&[^=]+=' + two + '(&|$)');
let input = 'file.php?&Valor1=one&Valor2=two&Valor3=three';
let output = input.replace(re, '');
console.log(output);
In this case, you need to make sure that your variable value does not contain any characters that have special meaning in regular expressions. If that's the case, you need to properly escape them.
Update
To address the input string in the updated question (no ampersand before first parameter):
let one = 'one';
let re = RegExp('([?&])[^=]+=' + one + '(&?|$)');
let input = 'file.php?Valor1=one&Valor2=two&Valor3=three';
let output = input.replace(re, '$1');
console.log(output);
You can use RegExp constructor, RegExp, template literal &[a-zA-Z]+\\d+=(?=${remove})${remove}) to match "&" followed by "a-z", "A-Z", followed by one or more digits followed by "", followed by matching value to pass to .replace()
var str = "file.php?&Valor1=one&Valor2=two&Valor3=three";
var re = function(not) {
return new RegExp(`&[a-zA-Z]+\\d+=(?=${not})${not}`)
}
var remove = "two";
var res = str.replace(re(remove), "");
console.log(res);
var remove = "one";
var res = str.replace(re(remove), "");
console.log(res);
var remove = "three";
var res = str.replace(re(remove), "");
console.log(res);
I think a much cleaner solution would be to use the URLSearchParams api
var paramsString = "Valor1=one&Valor2=two&Valor3=three"
var searchParams = new URLSearchParams(paramsString);
//Iterate the search parameters.
//Each element will be [key, value]
for (let p of searchParams) {
if (p[1] == "two") {
searchParams.delete(p[0]);
}
}
console.log(searchParams.toString()); //Valor1=one&Valor3=three

Editing a string using regex jquery [duplicate]

i have comma separated string like
var test = 1,3,4,5,6,
i want to remove particular character from this string using java script
can anyone suggests me?
JavaScript strings provide you with replace method which takes as a parameter a string of which the first instance is replaced or a RegEx, which if being global, replaces all instances.
Example:
var str = 'aba';
str.replace('a', ''); // results in 'ba'
str.replace(/a/g, ''); // results in 'b'
If you alert str - you will get back the same original string cause strings are immutable.
You will need to assign it back to the string :
str = str.replace('a', '');
Use replace and if you want to remove multiple occurrence of the character use
replace like this
var test = "1,3,4,5,6,";
var newTest = test.replace(/,/g, '-');
here newTest will became "1-3-4-5-6-"
you can make use of JavaScript replace() Method
var str="Visit Microsoft!";
var n=str.replace("Microsoft","My Blog");
var test = '1,3,4,5,6';​​
//to remove character
document.write(test.replace(/,/g, ''));
//to remove number
function removeNum(string, val){
var arr = string.split(',');
for(var i in arr){
if(arr[i] == val){
arr.splice(i, 1);
i--;
}
}
return arr.join(',');
}
var str = removeNum(test,3);
document.write(str); // output 1,4,5,6
You can also
var test1 = test.split(',');
delete test1[2];
var test2 = test1.toString();
Have fun :)
you can split the string by comma into an array and then remove the particular element [character or number or even string] from that array. once the element(s) removed, you can join the elements in the array into a string again
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
You can use this function
function removeComma(inputNumber,char='') {
return inputNumber.replace(/,/g, char);
}
Update
function removeComma(inputNumber) {
inputNumber = inputNumber.toString();
return Number(inputNumber.replace(/,/g, ''));
}

Categories