replace string from specific position until end Javascript - javascript

how can I replace a random String like:
2020-02-01T13:49
2020-02-01T04:27
2020-02-01T20:51
from starting with letter 'T'
So from T til the end of string I wanna replace it with T00:00
I have different Datetime Strings, so it should be flexible.

You have a couple of options:
replace
replace with a simple regular expression:
result = original.replace(/T.*$/, "T00:00");
That says "match T followed by anything through the end of the string".
indexOf and substring:
Alternatively, indexOf will tell you where the T is, then you can use substring:
const index = original.indexOf("T");
result = original.substring(0, index) + "T00:00";
split("T")[0]
You could also split on the T and only use the first string from the array:
result = original.split("T") + "T00:00";
I recommend a good read through the MDN documentation of String.

Related

Split and grab text before second hyphen

I have the following text string:
test-shirt-print
I want to filter the text string so that it only returns me:
test-shirt
Meaning that everything that comes after the second hyphen should be removed including the hyphen.
I am thinking that the solution could be to split on hyphen and somehow select the two first values, and combine them again.
I am unaware of which functionality is best practice to use here, I also thinking that if it would be possible to use a regular expression in order to be able to select everything before the second hyphen.
You can use split slice and join together to remove everything after the second hyphen
var str = "test-shirt-print";
console.log(str.split("-").slice(0, 2).join('-'))
You can try with String.prototype.slice()
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
and String.prototype.lastIndexOf()
The lastIndexOf() method returns the index within the calling String object of the last occurrence of the specified value, searching backwards from fromIndex. Returns -1 if the value is not found.
var str = 'test-shirt-print';
var res = str.slice(0, str.lastIndexOf('-'));
console.log(res);
You can also use split() to take the first two items and join them:
var str = 'test-shirt-print';
var res = str.split('-').slice(0,2).join('-');
console.log(res);

How to get only first character match with RegEx

I want to split a string in JavaScript using RegEX.
This is the example string:
REQUEST : LOREMLOREM : LOREM2LOREM2
Is it possible to split it into:
[REQUEST , LOREMLOREM : LOREM2LOREM2]
I've tried using /:?/g, but it doesn't work.
Instead of using a regex, you could split on a colon and then use a combination of shift to remove and return the first item from the array and join to concatenate the remaining items using a colon:
let str = "REQUEST : LOREMLOREM : LOREM2LOREM2";
$parts = str.split(':');
[a, b] = [$parts.shift().trim(), $parts.join(':').trim()];
console.log(a);
console.log(b);
You can simply do:
var parts = str.match(/([^:]*)\s*:\s*(.*)/).slice(1)
This will match the whole string and extract the two desired parts. The slice operation makes the result a plain array and removes the whole string from the results.
Just remove the Global modifier 'g' in the end and the '?' Quantifier. Without these the expression will return the first match only.
Your new RegEx will be /:/
For Testing your regular expressions go to https://regex101.com/r/11VFJ8/2

TS/JS split part of a string from regex match

In the past, I had this regex:
\{(.*?)\}
And entered this string:
logs/{thing:hi}/{thing:hello}
Then I used the following:
console.log(string.split(regex).filter((_, i) => i % 2 === 1));
To get this result:
thing:hi
thing:hello
For irrelevant design reasons, I changed my regex to:
\{.*?\}
But now, when using the same test string and split command, it returns only this:
/
I want it to return this:
{thing:hi}
{thing:hello}
How can I modify the split (or anything else) to do this?
Why not use match?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match
The match() method retrieves the matches when matching a string against a regular expression.
If you're only interested in returning the two string matches then it's much simpler than using split.
var foo = "logs/{thing:hi}/{thing:hello}";
console.log(foo.match(/{.*?}/g));

Get string between “-”

I have this string: 2015-07-023. I want to get 07 from this string.
I used RegExp like this
var regExp = /\(([^)]+-)\)/;
var matches = regExp.exec(id);
console.log(matches);
But I get null as output.
Any idea is appreciated on how to properly configure the RegExp.
The best way to do it is to not use RegEx at all, you can use regular JavaScript string methods:
var id_parts = id.split('-');
alert(id_parts[1]);
JavaScript string methods is often better than RegEx because it is faster, and it is more straight-forward and readable. Any programmer can read this code and quickly know that is is splitting the string into parts from id, and then getting the item at index 1
If you want regex, you can use following regex. Otherwise, it's better to go with string methods as in the answer by #vihan1086.
var str = '2015-07-023';
var matches = str.match(/-(\d+)-/)[1];
document.write(matches);
Regex Explanation
-: matches - literal
(): Capturing group
\d+: Matches one or more digits
Regex Visualization
EDIT
You can also use substr as follow, if the length of the required substring is fixed.
var str = '2015-07-023';
var newStr = str.substr(str.indexOf('-') + 1, 2);
document.write(newStr);
You may try the below positive lookahead based regex.
var string = "2015-07-02";
alert(string.match(/[^-]+(?=-[^-]*$)/))

How can I get a substring located between 2 quotes?

I have a string that looks like this: "the word you need is 'hello' ".
What's the best way to put 'hello' (but without the quotes) into a javascript variable? I imagine that the way to do this is with regex (which I know very little about) ?
Any help appreciated!
Use match():
> var s = "the word you need is 'hello' ";
> s.match(/'([^']+)'/)[1];
"hello"
This will match a starting ', followed by anything except ', and then the closing ', storing everything in between in the first captured group.
http://jsfiddle.net/Bbh6P/
var mystring = "the word you need is 'hello'"
var matches = mystring.match(/\'(.*?)\'/); //returns array
​alert(matches[1]);​
If you want to avoid regular expressions then you can use .split("'") to split the string at single quotes , then use jquery.map() to return just the odd indexed substrings, ie. an array of all single-quoted substrings.
var str = "the word you need is 'hello'";
var singleQuoted = $.map(str.split("'"), function(substr, i) {
return (i % 2) ? substr : null;
});
DEMO
CAUTION
This and other methods will get it wrong if one or more apostrophes (same as single quote) appear in the original string.

Categories