Change strings in Javascript with replace() based on index - javascript

I have the following string
let string = "01,15,01,45"
Which i want to turn to this
string = "01:15 - 01:45"
but i'm only able to come up with
"01,15,01,45".replace(/,/g, ':') // Gives "01:15:01:45"
but then i'm not sure how to get the index of the 5th position in string and replace it to ' - '
Any suggestion will be helpful.

Don't try doing things in one step when it would be clearer as multiple steps.
let string = "01,15,01,45";
let parts = string.split(",");
let result = `${parts[0]}:${parts[1]} - ${parts[2]}:${parts[3]}`;

let string = "01,15,01,45";
stringArray=string.split(',');
firstInterval=stringArray.slice(0, stringArray.length/2);
Output: ["01", "15"]
secondInterval=stringArray.slice(stringArray.length/2,stringArray.length);
Output:["01", "45"]
firstIntervalString=firstInterval[0]+":"+firstInterval[1];
Output: "01:15"
secondIntervalString=secondInterval[0]+":"+secondInterval[1];
Output: "01:45"
completeInterval=firstIntervalString+" - "+secondIntervalString;
Output: "01:15 - 01:45"
I think the code is self-explanatory. Still, please feel free to let me know if any part is not clear.

Another approach with matching pairs and replacing leftover commas.
let string = "01,15,01,45",
result = string.match(/\d\d,\d\d/g).map(p => p.replace(/\,/, ':')).join(' - ');
console.log(result);

Related

Javascript extract string from start to 0/, removing anything after 0/

I have a string which looks like this:
file:///storage/emulated/0/Pictures/IMG212.jpg
I want to remove anything from Pictures onwards so I would get this:
file:///storage/emulated/0/
How can I do this?
var regex = /^.*0\//
var matches = str.match(regex);
console.log(matches[0]);
You could find the index of /0 and use substring to select everything up to that point, like so:
const line = "file:///storage/emulated/0/Pictures/IMG212.jpg";
// Get the location of "/0", will be 24 in this example
const endIndex = line.indexOf("/0");
// Select everything from the start to the endIndex + 2
const result = line.substring(0, endIndex+2);
The reason why we add +2 to the endIndex is because the string that we're trying to find is 2 characters long:
file:///storage/emulated/0/Pictures/IMG212.jpg
[24]--^^--[25]
You can split the string using split method:
const myString = "file:///storage/emulated/0/Pictures/IMG212.jpg";
const result = myString.split("0/")[0] + "0/";
console.log(result); // file:///storage/emulated/0/
documentation for split method on MDN

Javascript get only matched text in regex

I have string like below
BANKNIFTY-13-FEB-2020-31200-ce
I want to convert the string to 13-FEB-31200-ce
so I tried below code
str.match(/(.*)-(?:.*)-(?:.*)-(.*)-(?:.*)-(?:.*)/g)
But its returning whole string
Two capture groups is probably the way to go. Now you have two options to use it. One is match which requires you to put the two pieces together
var str = 'BANKNIFTY-13-FEB-2020-31200-ce'
var match = str.match(/[^-]+-(\d{2}-[A-Z]{3}-)\d{4}-(.*)/)
// just reference the two groups
console.log(`${match[1]}${match[2]}`)
// or you can remove the match and join the remaining
match.shift()
console.log(match.join(''))
Or just string replace which you do the concatenation of the two capture groups in one line.
var str = 'BANKNIFTY-13-FEB-2020-31200-ce'
var match = str.replace(/[^-]+-(\d{2}-[A-Z]{3}-)\d{4}-(.*)/, '$1$2')
console.log(match)
Regex doesn't seem to be the most appropriate tool here. Why not use simple .split?
let str = 'BANKNIFTY-13-FEB-2020-31200-ce';
let splits = str.split('-');
let out = [splits[1], splits[2], splits[4], splits[5]].join('-');
console.log(out);
If you really want to use regexp,
let str = 'BANKNIFTY-13-FEB-2020-31200-ce';
let splits = str.match(/[^-]+/g);
let out = [splits[1], splits[2], splits[4], splits[5]].join('-');
console.log(out);
I would not use Regex at all if you know exact positions. Using regex is expensive and should be done differently if there is way. (https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/)
const strArr = "BANKNIFTY-13-FEB-2020-31200-ce".split("-"); // creates array
strArr.splice(0,1); // remove first item
strArr.splice(2,1); // remove 2020
const finalStr = strArr.join("-");
If the pattern doesn't need to be too specific.
Then just keep it simple and only capture what's needed.
Then glue the captured groups together.
let str = 'BANKNIFTY-13-FEB-2020-31200-ce';
let m = str.match(/^\w+-(\d{1,2}-[A-Z]{3})-\d+-(.*)$/)
let result = m ? m[1]+'-'+m[2] : undefined;
console.log(result);
In this regex, ^ is the start of the string and $ the end of the string.
You can have something like this by capturing groups with regex:
const regex = /(\d{2}\-\w{3})(\-\d{4})(\-\d{5}\-\w{2})/
const text = "BANKNIFTY-13-FEB-2020-31200-ce"
const [, a, b, c] = text.match(regex);
console.log(`${a}${c}`)

Regex to get the first element of each line

I'm trying to get the first element of each line, be it either a number or a string but when the line starts with a number, my current attempt still includes it:
const totalWords = "===========\n\n 1-test\n\n 2-ests \n\n 1 zfzrf";
const firstWord = totalWords.replace(/\s.*/,'')
The output I get :
1-test
2-ests
1 zfzrf
The output I would like:
1
2
1
Alternatively, if you are interested in a non-regexp version (should be faster)
var str = "===========\n\n 1-test\n\n 2-ests \n\n 1 zfzrf";
var res = str.split("\n");
for (row of res) {
let words = row.trim().split(' ');
let firstWord = words[0].trim();
// get first character, parse to int, validate it is infact integer
let element = firstWord.charAt(0);
if (Number.isInteger(parseInt(element))) {
console.log('Row', row);
console.log('Element: ', element);
}
}
Your Regex should skip leading spaces and then capture everything until a space or a dash, so you might want to go with ^\s*([^ -]+).
(See https://regex101.com/r/u7ELiw/1 for application to your examples)
If you additionally know exactly that you are looking for a single digit, you can instead go for ^\s*(\d)
(See https://regex101.com/r/IWhEQ1/1 again for applications)
Maybe im not too sure what you are asking but why are you using something as convoluted as regex when
line.charAt(0)
works pretty well?

How to detect the last 2 words using Javascript?

Hi sorry for the simple question but how can I detect the last two words in the String?
Let say I have this var:
var sample = "Hello World my first website";
How can I get the last two words dynamical. I tried the split().pop but only the last word is getting
var testing = sample.split(" ").pop();
console.log(testing)
Just try with:
var testing = sample.split(" ").splice(-2);
-2 takes two elements from the end of the given array.
Note that splice again give an array and to access the strings again the you need to use the index which is same as accessing directly from splitted array. Which is simply
var words =sample.split(" ");
var lastStr = words[words.length -1];
var lastButStr = words[words.length -2];
If you prefer the way you are doing. you are almost there. Pop() it again.
The pop() method removes the last element from an array and returns that element. This method changes the length of the array.
var sample = "Hello World my first website";
var words= sample.split(" ");
var lastStr = words.pop(); // removed the last.
var lastButStr= words.pop();
console.log(lastStr,lastButStr);
Note , pop() removes the element. And make sure you have enough words.
Or do it with a regex if you want it as a single string
var str = "The rain in SPAIN stays mainly in the plain";
var res = str.match(/[^ ]* [^ ]*$/g);
console.log(res);
var splitted = "Hello World my first website".split(" ");
var testing = splitted.splice(splitted.length - 2);
console.log(testing[0] + " " + testing[1]);
try this one
var sample = "Hello World my first website";
var testing = sample.split(" ").slice(-2);
console.log(testing)
You could also try something like:
sample.match(/\w+\W+\w+$/);
Try this.
var testing = sample.split(" ").splice(-2).join(' ');
First we have to split the string using split function,then by using splice we can get last two words and concatenate those two words by using join function.
please check this
sample.split(" ").splice(-2).join(" ");
The problem can be solved in several ways. the one I prefer is the following that splits the problem in sub problem:
transoform a sentence in an array
get last 2 items of an array
Transform a sentence in an array
let sentence = "Server Total Memory Capacity is: 16502288 MB";
let sentenceAsArray = sentence.split(' ');
Get last items of an array
let numberOfItems = 2;
let lastTwo = sentenceAsArray.splice(-numberOfItems)
Join array items
At the beginning we transformed a sentence into an array. Now we have to do the complementary operation: transform an array into a sentece.
let merged = lastTwo.join(' ')
Print into console
Now that we have new variable with desired content, can show it printing variable into the console with the following command.
console.log(merged)
You can use substr function
var sample = "Hello World my first website";
var testing = sample.substr(sample.length -2);

How to remove the last matched regex pattern in javascript

I have a text which goes like this...
var string = '~a=123~b=234~c=345~b=456'
I need to extract the string such that it splits into
['~a=123~b=234~c=345','']
That is, I need to split the string with /b=.*/ pattern but it should match the last found pattern. How to achieve this using RegEx?
Note: The numbers present after the equal is randomly generated.
Edit:
The above one was just an example. I did not make the question clear I guess.
Generalized String being...
<word1>=<random_alphanumeric_word>~<word2>=<random_alphanumeric_word>..~..~..<word2>=<random_alphanumeric_word>
All have random length and all wordi are alphabets, the whole string length is not fixed. the only text known would be <word2>. Hence I needed RegEx for it and pattern being /<word2>=.*/
This doesn't sound like a job for regexen considering that you want to extract a specific piece. Instead, you can just use lastIndexOf to split the string in two:
var lio = str.lastIndexOf('b=');
var arr = [];
var arr[0] = str.substr(0, lio);
var arr[1] = str.substr(lio);
http://jsfiddle.net/NJn6j/
I don't think I'd personally use a regex for this type of problem, but you can extract the last option pair with a regex like this:
var str = '~a=123~b=234~c=345~b=456';
var matches = str.match(/^(.*)~([^=]+=[^=]+)$/);
// matches[1] = "~a=123~b=234~c=345"
// matches[2] = "b=456"
Demo: http://jsfiddle.net/jfriend00/SGMRC/
Assuming the format is (~, alphanumeric name, =, and numbers) repeated arbitrary number of times. The most important assumption here is that ~ appear once for each name-value pair, and it doesn't appear in the name.
You can remove the last token by a simple replacement:
str.replace(/(.*)~.*/, '$1')
This works by using the greedy property of * to force it to match the last ~ in the input.
This can also be achieved with lastIndexOf, since you only need to know the index of the last ~:
str.substring(0, (str.lastIndexOf('~') + 1 || str.length() + 1) - 1)
(Well, I don't know if the code above is good JS or not... I would rather write in a few lines. The above is just for showing one-liner solution).
A RegExp that will give a result that you may could use is:
string.match(/[a-z]*?=(.*?((?=~)|$))/gi);
// ["a=123", "b=234", "c=345", "b=456"]
But in your case the simplest solution is to split the string before extract the content:
var results = string.split('~'); // ["", "a=123", "b=234", "c=345", "b=456"]
Now will be easy to extract the key and result to add to an object:
var myObj = {};
results.forEach(function (item) {
if(item) {
var r = item.split('=');
if (!myObj[r[0]]) {
myObj[r[0]] = [r[1]];
} else {
myObj[r[0]].push(r[1]);
}
}
});
console.log(myObj);
Object:
a: ["123"]
b: ["234", "456"]
c: ["345"]
(?=.*(~b=[^~]*))\1
will get it done in one match, but if there are duplicate entries it will go to the first. Performance also isn't great and if you string.replace it will destroy all duplicates. It would pass your example, but against '~a=123~b=234~c=345~b=234' it would go to the first 'b=234'.
.*(~b=[^~]*)
will run a lot faster, but it requires another step because the match comes out in a group:
var re = /.*(~b=[^~]*)/.exec(string);
var result = re[1]; //~b=234
var array = string.split(re[1]);
This method will also have the with exact duplicates. Another option is:
var regex = /.*(~b=[^~]*)/g;
var re = regex.exec(string);
var result = re[1];
// if you want an array from either side of the string:
var array = [string.slice(0, regex.lastIndex - re[1].length - 1), string.slice(regex.lastIndex, string.length)];
This actually finds the exact location of the last match and removes it regex.lastIndex - re[1].length - 1 is my guess for the index to remove the ellipsis from the leading side, but I didn't test it so it might be off by 1.

Categories

Resources