Remove all characters of a string after the fourth space - javascript

Im looking for a way to remove the fourth space, (and everything following it) from a string ,this function to be for every line list from "input text area"
Example: if i have a list "Vertically" in Input text area( i will use here days of the week just for example:
Monday February 8 2016 08:05:07 GMT-0700 (PDT)
Tuesday February 9 2016 09:07:07 GMT-0700 (PDT)
Wednesday February 10 2016 01:04:07 GMT-0700 (PDT)
Thursday February 11 2016 05:15:07 GMT-0700 (PDT)
etc
when i click button remove ,results in Output Textarea to be "Vertically" like this:
Monday February 8 2016
Tuesday February 9 2016
Wednesday February 10 2016
Thursday February 11 2016
i used this script, its work good for 1st line ,but just for first line ,i want to work for all lines. Please help me ,im trying to maked myself searching in stackoverflow but without succes ,pleas can somone modify my script or tell me what i maked wrong, thank you so much.
this is my script:
function remove_list() {
var count = 0;
var list = document.myForm.Input.value;
list = list.replace(/^((?:[^ ]* ){3}[^ ]*) [\S\s]*/, "$1");
var listvalues = new Array();
var newlist = new Array();
listvalues = list.split(/[\s,]+/).join("");
var hash = new Object();
for (var i = 0; i < listvalues.length; i++) {
if (hash[listvalues[i].toLowerCase()] != 0) {
newlist = newlist.concat(listvalues[i]);
hash[listvalues[i].toLowerCase()] = 1
} else {
count++;
}
}
document.myForm.Output.value = newlist.join("");
}

Your regular expression almost works.
If you want it to work for multiple lines, you could use the m multi-line flag so that the anchors ^/$ match the start/end of each line rather than the start/end of the string.
Here is your revised regular expression:
/^((?:[^ ]* ){3}[^ ]*) [\S\s]*?$/gm
However, you could actually simplify it to the following:
/^((?:\S+\s+){3}\S+).*$/gm
Usage:
textarea.value.replace(/^((?:\S+\s+){3}\S+).*$/gm, '$1');
Explanation:
gm - Global flag; multi-line flag
^ - Anchor asserting the start of each line
((?:\S+\s+){3}\S+) - Capturing group to match one or more non-whitespace chracters followed by one or more whitespace characters three times; then match one or more non-whitespace characters again until the forth whitespace character
.* - Match the remaining characters on the line
$ - Anchor asserting the end of each line.
Here is an example demonstrating this:
var textarea = document.querySelector('textarea');
var replacedValue = textarea.value.replace(/^((?:\S+\s+){3}\S+).*$/gm, '$1');
document.getElementById('output').textContent = replacedValue;
<textarea>
Monday February 8 2016 08:05:07 GMT-0700 (PDT)
Tuesday February 9 2016 09:07:07 GMT-0700 (PDT)
Wednesday February 10 2016 01:04:07 GMT-0700 (PDT)
Thursday February 11 2016 05:15:07 GMT-0700 (PDT)
</textarea>
<p>Output:</p>
<pre id="output"></pre>

You are making that way more complicated with regex than you need to. All you really need to do is split the whole thing on new lines, loop through those, split on spaces, and then rejoin a spliced version.
function removeExtra() {
var ta = document.getElementById('lines'),
lines = ta.innerHTML,
reformatted = [];
lines = lines.split("\n");
for(var i = 0; i < lines.length; i++){
var parts = lines[i].split(" ");
reformatted.push( parts.splice(0, 4).join(" ") );
}
ta.innerHTML = reformatted.join("\n");
}
full fiddle at https://jsfiddle.net/w7z88vjv/

Related

How to split Suffix from a number using jquery?

How can I convert this: NIFTY 16th JAN 12300 CE into NIFTY 16<sup>th</sup> JAN 12300 CE using jQuery?
To achieve this you can use a regular expression. To help negate the possibility of a false positive when the target string occurs within a word you can have the regex look specifically for the st, nd, rd or th strings when they follow an integer of 1 or 2 characters in length. Try this:
["NIFTY 16th JAN 12300 CE", "rd ND 21st April"].forEach(v => {
let output = v.replace(/(\d{1,2})(st|nd|rd|th)/gi, '$1<sup>$2</sup>');
console.log(output);
});
You can split th and rejoin with <sup>th</sup>
var x = "NIFTY 16th JAN 12300 CE";
var y = x.split("th").join("<sup>th</sup>");
console.log(y);
Here is the working code for the given requirement.
It works by identifying the day number, day suffix and replacing the pattern with required one.
var input = "NIFTY 16th JAN 12300 CE";
// Get the day string (Examples: 16th / 3rd)
var dayString = input.match(/[0-9]+[a-zA-Z]+/g);
// Get the day-number and day-suffix
var dayNumber = dayString.toString().match(/[0-9]+/i);
var daySuffix = dayString.toString().match(/[a-zA-Z]+/i);
// Print the output
console.log(dayNumber + "<sup>" + daySuffix + "</sup>");

regex For Flight no and Date

I have the following string
XX1366**A**Monday 5 November 2018XX4515**B**Monday 5 November 2018XX3416**C**Monday 17 December 2018XX1744**D**Tuesday 18 December 2018
Want to extract the data in below format:
Flight No : XX1366,XX4515,XX3416,XX1744
Flight Date : Monday 5 November 2018, Monday 5 November 2018, Monday 17 December 2018, Tuesday 18 December 2018
My Code : A, B, C, D (which is after the Flight No)
Could you help me to extract this data using regular expression?
This may be a bit laggy but should work, you can adapt it easily :
(XX[0-9]+)([A-Z])([a-zA-Z]+ [0-9]+ [a-zA-Z]+ [0-9]+)
Pleas note that you can always test your regex online at sites like https://regexr.com/
Surely not the most elegant solution, however the following works too:
XX(\d*)(\w)(\w*\s\d+\s\w*\s\d*)
As a sidenote in case you're wondering - people on the website are far more likely to answer your question if you have put in some effort beforehand. Basically it's a forum for coding help, rather than on-demand code-writers. :)
On option could be to use 2 capturing groups to match either XX followed by 4 digits or match any character and use a positive lookahead to assert that what followed is XX followed by 4 digits or the end of the string $
Then while looping the matches collect the values in an array and use join to show them comma separated.
(XX\d{4})\*\*[A-Z]\*\*|(.*?(?=XX\d{4}|$))
Regex demo
const regex = /(XX\d{4})\*\*[A-Z]\*\*|(.*?(?=XX\d{4}|$))/g;
const str = `XX1366**A**Monday 5 November 2018XX4515**B**Monday 5 November 2018XX3416**C**Monday 17 December 2018XX1744**D**Tuesday 18 December 2018`;
let m;
let flights = [];
let flightDates = [];
while ((m = regex.exec(str)) !== null) {
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if (m[1]) {
flights.push(m[1]);
}
if (m[2]) {
flightDates.push(m[2]);
}
}
console.log("Flight No: " + flights.join(','));
console.log("Flight Date: " + flightDates.join(', '));
Or you might use a combination of map and split to create a multidemensional array where the first value is for example XX1366 and the second Monday 5 November 2018 and you could extract those values. First split on the positive lookahead (?=XX\d{4}) and then split on matching \*\*[A-Z]\*\*
const str = `XX1366**A**Monday 5 November 2018XX4515**B**Monday 5 November 2018XX3416**C**Monday 17 December 2018XX1744**D**Tuesday 18 December 2018`;
let res = str.split(/(?=XX\d{4})/)
.map(x => x.split(/\*\*[A-Z]\*\*/)
);
const str = `XX1366**A**Monday 5 November 2018XX4515**B**Monday 5 November 2018XX3416**C**Monday 17 December 2018XX1744**D**Tuesday 18 December 2018`;
let res = str.split(/(?=XX\d{4})/)
.map(x => x.split(/\*\*[A-Z]\*\*/));
console.log("Flight No: " + res.map(x => x[0]).join(', '));
console.log("Flight Date: " + res.map(x => x[1]).join(', '));
I think this regex can help you :
Flight No : (XX[0-9]+)
Flight Date : [MTWFS][a-z]+ [0-9]{1,2} [a-zA-Z]+ [0-9]{4}
Code : (?<=\*)([A-Z])
You can use /y flag to match at last Index.

extract IP on large text using AppleScript / JavaScript

I'm try to selecting a large text and extract all the IP from this text.
E.g
fdsfsfsdfsd 36.23.227.234 Paris,FR FKGNGH 2df2df5cdsss 12151281250 November
23d, 2014 November 23d,
2014 titlethere 6928699 dfgdfgdfg REWG50 US$50.00
fdsfddfseed 96.8.225.128 London,UK FDGSDS ASDGSDG22GDS 33583855464 January
30d, 2011 January 30d, 2011 titlethere 34576874 dsfasdg
ASASDF41 US€0.00
the result would be 36.23.227.234 96.8.225.128
Is this possible ? as the data is very random ? can AppleScript or maybe more javascript I'm guessing can do this?
You can use regular expressions match() function in JavaScript:
var str = 'fdsfsfsdfsd 36.23.227.234 Paris,FR FKGNGH 2df2df5cdsss 12151281250 November 23d, 2014 November 23d, 2014 titlethere 6928699 dfgdfgdfg REWG50 US$50.00 fdsfddfseed 96.8.225.128 London,UK FDGSDS ASDGSDG22GDS 33583855464 January 30d, 2011 January 30d, 2011 titlethere 34576874 dsfasdg ASASDF41 US€0.00';
var regexp = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/gi;
var matches_array = str.match(regexp);
console.log(matches_array);
Which gives you Array [ "36.23.227.234", "96.8.225.128" ]
See https://stackoverflow.com/a/41610014 for all occurences of a string and https://stackoverflow.com/a/32689475 for regex to find IP addresses.

Regular expression to fetch year from date - Javascript

Can somebody please help me construct a regular expression in Javascript to check if year 2017 exists or a year starting with 19 or 20 (century) exists in a given date.
My date format is : Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time).
I tried this but it fails:
var str = "Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)";
var patt = new RegExp("/^\S{3}[\s]\S{3}[\s]\d{2}[\s]\d{4}$/");
var res = patt.test(str);
Thanks,
Haseena
You can use Date.getFullYear() method.
var d = new Date("Fri Dec 01 1999 00:00:00 GMT-0800 (Pacific Standard Time)");
var year = d.getFullYear();
Here is example you can use.
var str="Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)";
var patt=/(\w{3}\s){2}\d{2}\s(\d{4})\s(.*)/;
var results = patt.exec(str);
console.log(results);
console.log(results[2]);
The second group is match the year.
The year validation with multiple condition is not quite a regex thingy
If I have understood your question then you can try this:
^[a-zA-Z]{3}\s+[A-Za-z]{3}\s+\d{2}\s+(2017|(?:19\d{2}|20\d{2}))\s+.*
It will only match if the year is 2017
It will match if the year starts with 19
It will match if the year starts with 20
If match is found, then the year can be found in group 1
Explanation
const regex = /^[a-zA-Z]{3}\s+[A-Za-z]{3}\s+\d{2}\s+(2017|(?:19\d{2}|20\d{2}))\s+.*$/gm;
const str = `Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)`;
let m;
if((m = regex.exec(str)) !== null) {
console.log("Full match ="+m[0]);
console.log("Matched year ="+m[1]);
}
else
console.log("no match found");
With a fixed date format, this is really easy:
First, just extract your year using a regular expression var year = str.match(/^.{11}(\d{4})/)[1]
.match returns an array where the first element is the entire matched string and subsequent elements are the parts captured in parentheses.
After you have this, you can test if year === '2017' or if year.substr(0, 2) === '19'.
There are about a dozen other ways to do this, too.
var myDate = 'Fri Dec 01 2017 00:00:00 GMT-0800 (Pacific Standard Time)';
function isCorrectYear(dateString) {
var year = dateString.match(/^.{11}(\d{4})/)[1];
if (year === '2017') return true;
}
if (isCorrectYear(myDate)) {
alert("It's the correct year.");
}
Something just occurred to me... "year 2017 exists or a year starting with 19 or 20". Doesn't that cover every year in every date string you are ever likely to encounter? I don't think they had Javascript before the 1900s and I doubt anything any of us will write will still be in use after the year 2100.

regex date format

What would the regex string expression be for the following date formats?
09 Jan 2012
09/01/2012
No minimum or max. I have a javascript file which stores all regex's, such as:
var saNumberRegEx = /(^0[87][23467]((\d{7})|( |-)((\d{3}))( |-)(\d{4})|( |-)(\d{7})))/;
var tagNameRegEx = /^[a-z0-9][-\.a-z0-9]{4,29}$/i;
Thank you
/^\d{2}\s\w{3}\s\d{4}$/.test('09 Jan 2012'); // true
/^\d{2}\/\d{2}\/\d{4}$/.test('09/01/2012'); // true
/^\d{2}\s\w{3}\s\d{4}\s\d{2}\/\d{2}\/\d{4}$/.test('09 Jan 2012 09/01/2012'); // true
Edit:
Sample 1
/^\d{2} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4}$/
Sample 2
/^\d{2}/\d{2}/\d{4}$/
For the first kind (09 Jan 2012):
/\d{2} [a-z]{3} \d{4}/i
For the second kind (09/01/2012):
/\d{2}\/\d{2}\/\d{4}/
/^(\d{1,2})[\-./ ](\d{1,2})[\-./ ](\d{4})$/.test('09/12/2012');//Just for month taken as number
/^(\d{1,2})[\-./ ](Jan|Feb|Mars|Avril|Mai|Juin|Juil|Aout|Sept|Oct|Nov|Dec)[\-./ ](\d{4})$/.test('09 Jan 2012');//True just for month taken as word ex: jan/Dec
/^(\d{1,2})[\-./ ](?:(\d{1,2})|(Jan|Feb|Mars|Avril|Mai|Juin|Juil|Aout|Sept|Oct|Nov|Dec))[\-./ ](\d{4})$/.test('09/12/2012');//True,Mixed month can be any number or word of month
/^(\d{1,2})[\-./ ](?:(\d{1,2})|(Jan|Feb|Mars|Avril|Mai|Juin|Juil|Aout|Sept|Oct|Nov|Dec))[\-./ ](\d{4})$/.test('09 Jan 2012');// TRue,Mixed month can be any number or word of month
/^(\d{1,2})[\-./ ](?:(\d{1,2})|(Jan|Feb|Mars|Avril|Mai|Juin|Juil|Aout|Sept|Oct|Nov|Dec))[\-./ ](\d{4})$/.test('09-Jan-2012');//True, Mixed month can be any number or word of month

Categories