Javascript split by numbers using regex - javascript

I'm trying to come up with a regex that will do following.
I have a string
var input_string = "E100T10P200E3000T3S10";
var output=input_string.split(**Trying to find this**);
this should give an array with all the letters in order with repetitions
output = ["E","T","P","E","T","S"]

See below. \d+ means one or more digits; filter (x => x) removes empty strings that can appear in the beginning or the end of the array if the input string begins or ends with digits.
var input_string = "E100T10P200E3000T3S10";
var output = input_string.split (/\d+/).filter (x => x);
console.log (output);

We can try just matching for capital letters here:
var input_string = "E100T10P200E3000T3S10";
var output = input_string.match(/[A-Z]/g);
console.log(output);

Another approach is spread the string to array and use isNaN as filter callback
var input_string = "E100T10P200E3000T3S10";
var output = [...input_string].filter(isNaN);
console.log(output);

You can use regex replace method. First replace all the digits with empty string and then split the resultant string.
const input_string = 'E100T10P200E3000T3S10';
const ret = input_string.replace(/\d/g, '').split('');
console.log(ret);

Related

Getting second digit in a string using Javascript + Regex?

I'm wondering how I can get the second digit of a string where we don't know the number of digits the second number will be and without using splice or substring.
Ex. Channel.0.This.13
Should Return: 13
I've seen a few similar questions but they
typically know the number of digits the second number will be or
use splicing and substring, which I do not want to use in this case.
I appreciate the help :)
You could use String.prototype.match
In case that the string does not have any number, which matches will return null, you should use optional chaining ?. for a safer array index access
const str = "Channel.0.This.13";
const res = str.match(/\d+/g)?.[1];
console.log(res);
Use this regex (\d*)$. This will return only group with numbers which in the end of the string.
try this:
^[^\d]*\d+[^\d]+(\d+).*
Example:
const secondDigit = "Channel.0.This.13".match(/^[^\d]*\d+[^\d]+(\d+).*/).pop();
console.log(Number(secondDigit)); // 13
Assuming the original string contains only alphabets, numbers and '.' (in between),
Here is my solution (Pseudo code):
String givenString;
regex=/([0-9]+)(\.[a-zA-Z]+)?(\.[0-9]+)/;
//below code will return an array or null (if no second number is present)
match=givenString.match(regex);
//access last element of array. It will be like '.13' , just remove '.' and you are good to go
match.pop()
Javascript Regex Docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges
String.prototype.match() returns an array whose contents depend on the presence or absence of the global (g) flag, or null
const input1 = "Channel.0.This.13",
input2 = "Channel.0.This",
input3 = "Channel.This.";
const digitMatch = function (input) {
const digits = input.match(/\d+/g);
return (digits && digits[1]) || "Not Found";
};
console.log(digitMatch(input1));
console.log(digitMatch(input2));
console.log(digitMatch(input3));
if no matches are found.
It will help .*?\d+.*?(\d+).*$
"Channel.0.This.13.Channel.0.This.56".match(/.*?\d+.*?(\d+).*$/).pop()
// Output: 13
"Channel.0.This.13".match(/.*?\d+.*?(\d+).*$/).pop()
// Output: 13
You can reference the regex .match() key. str.match(reg)[1]
const str1 = 'Channel.0.This.13'
const str2 = 'some.otherStrin8..'
const str3 = '65 people.For.&*=20.them,98'
const regex = /\d+/g
function matchSecond(str, reg) {
str.match(reg)[1] ? output = str.match(reg)[1] : output = false
return output;
}
console.log(matchSecond(str1,regex))
console.log(matchSecond(str2,regex))
console.log(matchSecond(str3,regex))

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}`)

JavaScript Split with RegEx without Global Match

I have an expression.
var expression = "Q101='You will have an answer here like a string for instance.'"
I have a regular expression that searches the expression.
var regEx = new regExp(/=|<>|like/)
I want to split the expression using the regular expression.
var result = expression.split(regExp)
This will return the following:
["Q101", "'You will have an answer here ", " a string for instance'"]
This is not what I want.
I should have:
["Q101", "'You will have an answer here like a string for instance'"]
How do I use the regular expression above to split only on the first match?
Since you only want to grab the two parts either side of the first delimiter it might be easier to use String.match and discard the whole match:
var expression = "Q101='You will have an answer here like a string for instance.'";
var parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);
expression = "Q101like'This answer uses like twice'";
parts = expression.match(/^(.*?)(?:=|<>|like)(.*)$/);
parts.shift();
console.log(parts);
JavaScript's split method won't quite do what you want, because it will either split on all matches, or stop after N matches. You need an extra step to find the first match, then split once by the first match using a custom function:
function splitMatch(string, match) {
var splitString = match[0];
var result = [
expression.slice(0, match.index),
expression.slice(match.index + splitString.length)
];
return result;
}
var expression = "Q101='You will have an answer here like a string for instance.'"
var regEx = new RegExp(/=|<>|like/)
var match = regEx.exec(expression)
if (match) {
var result = splitMatch(expression, match);
console.log(result);
}
While JavaScript's split method does have an optional limit parameter, it simply discards the parts of the result that make it too long (unlike, e.g. Python's split). To do this in JS, you'll need to split it manually, considering the length of the match —
const exp = "Q101='You will have an answer here like a string for instance.'"
const splitRxp = /=|<>|like/
const splitPos = exp.search(splitRxp)
const splitStr = exp.match(splitRxp)[0]
const result = splitPos != -1 ? (
[
exp.substring(0, splitPos),
exp.substring(splitPos + splitStr.length),
]
) : (
null
);
console.log(result)

Javascript regex capture giving unexpected results

I am trying to capture all data before the first _. What I have so far is
const regex = /(.*)(?=_)/g;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
The output is an array Array ["Mike_Jones","" ]
What I was expecting was Mike
Use /^[^_]*/
^ looks from the beginning of the string
[^_] negates the _
* gives any number of characters
const regex = /^[^_]*/;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
var s = "Mike_Jones_Jr";
console.log(s.split('_')[0]);
Create a capture group ((something between parentheses)) that starts at the beginning of the line (^) and is lazy (.*?), then grab the second item in the matching array.
const regex = /(^.*?)_/s
console.log('Mike_Jones_Jr'.match(regex)[1] || '')
console.log(`Mike
_Jones_Jr`.match(regex)[1] || '')
You can simply use split,
Note:- Second parameter is to limit the number of elements in final outptut
var s = "Mike_Jones_Jr";
console.log( s.split('_', 1) );
If you want to do using regex, you can drop the g flag
const regex = /^[^_]*(?=_)/;
var s = "Mike_Jones_Jr";
console.log(s.match(regex));
console.log("_ melpomene is awesome".match(regex));

Finding white space in string and replace that with another in an array

I have a set of strings in array like ['1254','1556',' 515']. From here I want to look for a string which has a white space and three digits. Also I want to replace that string with ----. How can I do that as the strings are in an array?
You could take a regular expression for testing the string and replace the value for a new array.
var array = ['1254','1556',' 515'],
result = array.map(s => /^\s\d{3}$/.test(s) ? '----' : s);
console.log(result);
You can use
^(?=.* )(?=.*\d{3})[\d\s]+$
let arr = ['1254','1556',' 515']
let replaceStr = (str) => {
return str.replace(/^(?=.* )(?=.*\d{3})[\d\s]+$/,(match)=> '-'.repeat(match.length))
}
let final = arr.map(replaceStr)
console.log(final)

Categories

Resources