How to split a string after a date in Javascript? - javascript

I have the string "11/21/2018 11/27/2018 Thanksgiving Break" and would like to cut both dates from it and only retrieve both dates (11/21/2018) and (11/27/2018) as well as the title in some form of array.

You can match the dates and everything else while replacing groups like this:
const str = "11/21/2018 11/27/2018 Thanksgiving Break";
const ans = [];
str.replace(/(\d{2}\/\d{2}\/\d{4}) |(.+$)/g, (_, date, text) => {
ans.push(date || text);
});
console.log(ans);
You can see how the regex groups matches here: https://regex101.com/r/IXW6Hv/1

You could use split method.
let str = "11/21/2018 11/27/2018 Thanksgiving Break"
let endOfFirstDate = str.indexOf(" ")
let firstDate = str.substring(0, endOfFirstDate).trim()
let endOfSecondDate = str.indexOf(" ", endOfFirstDate + 1)
let secondDate = str.substring(endOfFirstDate, endOfSecondDate).trim()
let title = str.substring(endOfSecondDate, str.length).trim()

This is commonly done using Regular expressions:
const text = "11/21/2018 11/27/2018 Thanksgiving Break";
console.log(text.match(/([0-9\/]+\s){2}(.+)/)[2])
A more basic way is to split the string into words, remove the first two, then join it again:
const text = "11/21/2018 11/27/2018 Thanksgiving Break";
console.log(text.split(" ").splice(2).join(" "))

if your date is always dd/mm/yyyy style, you can try this one to test it.
let str = "11/21/2018 11/27/2018 Thanksgiving Break"
let tmp = str;
tmp = tmp.replace(/[\d]+\/[\d]+\/[\d]+/g," ")
let arr = tmp.split(" ");
for(const item of arr){
if(item){
str = str.replace(item," ");
}
}
for(const item of str.split(" ")){
if(item){
console.log(item);
}
}
if all your data are separate by space, you can try a simple one like below:
let str = "11/21/2018 11/27/2018 Thanksgiving Break"
let arr = str.split(" ");
for(const item of arr){
if(/[\d]+\/[\d]+\/[\d]+/.test(item)){
console.log(item);
}
}

Related

Is it possible to replace only one character in a string if that character appears twice consecutively?

So I made a method to make the first letter of all the words in any string Uppercase.
String.prototype.toMyCase = function () {
let strArray = Array.from(this.split(" "));
for(let i=0; i<strArray.length; i++){
strArray[i] = strArray[i][0].toUpperCase() + strArray[i].substr(1);
}
let newStr = strArray.toString();
let finalStr = newStr.replace(/,/g, " ");
return finalStr;
};
The problem with this is when I pass a string that has real commas(,) it replace that comma(,) too in the finalStr step. For e.g
console.log("How can mirrors be real, if our eyes aren't real".toMyCase(); gives me
How Can Mirrors Be Real If Our Eyes Aren't Real (there are two spaces after Real).
You can use strArray.join(' ');
String.prototype.toMyCase = function () {
let strArray = Array.from(this.split(" "));
for(let i=0; i<strArray.length; i++){
strArray[i] = strArray[i][0].toUpperCase() + strArray[i].substr(1);
}
return strArray.join(' ');
};
console.log("How can mirrors be real, if our eyes aren't real".toMyCase());
How about with this single line soln after string split(), uppercase first character and join the rest using .map() with the first?,
let str = "How can mirrors be real, if our eyes aren't real";
let captialized_words = str => str.split(' ').map(w => w.substring(0, 1).toUpperCase() + w.substring(1)).join(' ')
console.log(captialized_words(str))
Instead of
let finalStr = newStr.replace(/,/g, " ");
Do
let finalStr = newStr.replace(/,/g, "");

How to get the delimiters that split my string in Javascript?

Let's say I have a string like the following:
var str = "hello=world&universe";
And my regex replace statement goes like this:
str.replace(/([&=])/g, ' ');
How do I get the delimiters that split my string from the above regex replace statement?
I would like the result to be something like this:
var strings = ['hello', 'world', 'universe'];
var delimiters = ['=', '&'];
You could split with a group and then separate the parts.
var str = "hello=world&universe",
[words, delimiters] = str
.split(/([&=])/)
.reduce((r, s, i) => {
r[i % 2].push(s);
return r;
}, [[], []]);
console.log(words);
console.log(delimiters);
Here's one way using String.matchAll
const str = "hello=world&universe";
const re = /([&=])/g;
const matches = [];
let pos = 0;
const delimiters = [...str.matchAll(re)].map(m => {
const [match, capture] = m;
matches.push(str.substring(pos, m.index));
pos = m.index + match.length;
return match;
});
matches.push(str.substring(pos));
console.log('matches:', matches.join(', '));
console.log('delimiters:', delimiters.join(', '));
But just FYI. The string you posted looks like a URL search string. You probably want to use URLSearchParams to parse it as there are edge cases if you try to split on both '&' and '=' at the same time. See How can I get query string values in JavaScript?

How to split two dimensional array in JavaScript?

I have string like below:
"test[2][1]"
"test[2][2]"
etc
Now, I want to split this string to like this:
split[0] = "test"
split[1] = 2
split[2] = 1
split[0] = "test"
split[1] = 2
split[2] = 2
I tried split in javascript but no success.How can it be possible?
CODE:
string.split('][');
Thanks.
Try this:
.replace(/]/g, '') gets rid of the right square bracket.
.split('[') splits the remaining "test[2[1" into its components.
var str1 = "test[2][1]";
var str2 = "test[2][2]";
var split = str1.replace(/]/g, '').split('[');
var split2 = str2.replace(/]/g, '').split('[');
alert(split);
alert(split2);
you can try :
string.split(/\]?\[|\]\[?/)
function splitter (string) {
var arr = string.split('['),
result = [];
arr.forEach(function (item) {
item = item.replace(/]$/, '');
result.push(item);
})
return result;
}
console.log(splitter("test[2][1]"));
As long as this format is used you can do
var text = "test[1][2]";
var split = text.match(/\w+/g);
But you will run into problems if the three parts contain something else than letters and numbers.
You can split with the [ character and then remove last character from all the elements except the first.
var str = "test[2][2]";
var res = str.split("[");
for(var i=1, len=res.length; i < len; i++) res[i]=res[i].slice(0,-1);
alert(res);

How to get substring value from main string?

I have string similar to this one.
HTML
var str = "samplestring=:customerid and samplestring1=:dept";
JS
var parts = str.split(':');
var answer = parts;
I want to trim substrings which starts with colon: symbol from the main string
But it is returing the value like this
samplestring=,customerid and samplestring1=,dept
But I want it something like this.
customerid,dept
I am getting main string dynamically it may have colon more then 2.
I have created a fiddle also link
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.match(/:(\w+)/g).map(function(s){return s.substr(1)}).join(","))
you can try regex:
var matches = str.match(/=:(\w+)/g);
var answer = [];
if(matches){
matches.forEach(function(s){
answer.push(s.substr(2));
});
}
Here's a one-liner:
$.map(str.match(/:(\w+)/g), function(e, v) { return e.substr(1); }).join(",")
Try
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(':');
var dept = parts[2];
var cus_id = parts[1].split(' and ')[0];
alert(cus_id + ", " + dept );
Using this you will get o/p like :customerid,dept
this will give you what you need...
var str = "samplestring=:customerid and samplestring1=:dept";
var parts = str.split(' and ');
var answer = [];
for (var i = 0; i < parts.length; i++) {
answer.push(parts[i].substring(parts[i].indexOf(':')+1));
}
alert(answer);
var str = "samplestring=:customerid and samplestring1=:dept";
alert(str.replace(/[^:]*:(\w+)/g, ",$1").substr(1))
You can try it like this
var str = "samplestring=:customerid and samplestring1=:dept and samplestring11=:dept";
var results = [];
var parts = str.split(' and ');
$.each(parts, function( key, value ) {
results.push(value.split(':')[1]);
});
Now the results array contains the three values customerid, dept, and dept
Here \S where S is capital is to get not space characters so it will get the word till first space match it, so it will match the word after : till the first space and we use /g to not only match the fisrt word and continue search in the string for other matches:
str.match(/:(\S*)/g).map(function(s){return s.substr(1)}).join(",")

Get first word of string

Okay, here is my code with details of what I have tried to do:
var str = "Hello m|sss sss|mmm ss";
//Now I separate them by "|"
var str1 = str.split("|");
//Now I want to get the first word of every split-ed sting parts:
for (var i = 0; i < codelines.length; i++) {
//What to do here to get the first word of every spilt
}
So what should I do there? :\
What I want to get is :
firstword[0] will give "Hello"
firstword[1] will give "sss"
firstword[2] will give "mmm"
Use regular expression
var totalWords = "foo love bar very much.";
var firstWord = totalWords.replace(/ .*/,'');
$('body').append(firstWord);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Split again by a whitespace:
var firstWords = [];
for (var i=0;i<codelines.length;i++)
{
var words = codelines[i].split(" ");
firstWords.push(words[0]);
}
Or use String.prototype.substr() (probably faster):
var firstWords = [];
for (var i=0;i<codelines.length;i++)
{
var codeLine = codelines[i];
var firstWord = codeLine.substr(0, codeLine.indexOf(" "));
  firstWords.push(firstWord);
}
To get first word of string you can do this:
let myStr = "Hello World"
let firstWord = myStr.split(" ")[0]
console.log(firstWord)
split(" ") will convert your string into an array of words (substrings resulted from the division of the string using space as divider) and then you can get the first word accessing the first array element with [0].
See more about the split method.
I 'm using this :
function getFirstWord(str) {
let spaceIndex = str.indexOf(' ');
return spaceIndex === -1 ? str : str.substring(0, spaceIndex);
};
How about using underscorejs
str = "There are so many places on earth that I want to go, i just dont have time. :("
firstWord = _.first( str.split(" ") )
An improvement upon previous answers (working on multi-line or tabbed strings):
String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}
Or using search and substr:
String.prototype.firstWord = function(){let sp=this.search(/\s/);return sp<0?this:this.substr(0,sp)}
Or without regex:
String.prototype.firstWord = function(){
let sps=[this.indexOf(' '),this.indexOf('\u000A'),this.indexOf('\u0009')].
filter((e)=>e!==-1);
return sps.length? this.substr(0,Math.min(...sps)) : this;
}
Examples:
String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}
console.log(`linebreak
example 1`.firstWord()); // -> linebreak
console.log('space example 2'.firstWord()); // -> singleline
console.log('tab example 3'.firstWord()); // -> tab
var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');
//Now i want to get the first word of every split-ed sting parts:
for (var i=0;i<str1.length;i++)
{
//What to do here to get the first word :)
var firstWord = str1[i].split(' ')[0];
alert(firstWord);
}
This code should get you the first word,
var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');
//Now i want to get the first word of every split-ed sting parts:
for (var i=0;i<str1.length;i++)
{
//What to do here to get the first word :(
var words = str1[i].split(" ");
console.log(words[0]);
}
In modern JS, this is simplified, and you can write something like this:
const firstWords = str =>
str .split (/\|/) .map (s => s .split (/\s+/) [0])
const str = "Hello m|sss sss|mmm ss"
console .log (firstWords (str))
We first split the string on the | and then split each string in the resulting array on any white space, keeping only the first one.
I'm surprised this method hasn't been mentioned: "Some string".split(' ').shift()
To answer the question directly:
let firstWords = []
let str = "Hello m|sss sss|mmm ss";
const codeLines = str.split("|");
for (var i = 0; i < codeLines.length; i++) {
const first = codeLines[i].split(' ').shift()
firstWords.push(first)
}
const getFirstWord = string => {
const firstWord = [];
for (let i = 0; i < string.length; i += 1) {
if (string[i] === ' ') break;
firstWord.push(string[i]);
}
return firstWord.join('');
};
console.log(getFirstWord('Hello World'));
or simplify it:
const getFirstWord = string => {
const words = string.split(' ');
return words[0];
};
console.log(getFirstWord('Hello World'));
This code should get you the first word,
const myName = 'Jahid Bhuiyan';
console.log(myName.slice(0, myName.indexOf(' ')));
Ans will be "Jahid"

Categories

Resources