Get the integer value an attribute in a string in javascript - javascript

I have a string that could look like these:
"length=10, width=40, height=80"
"length=10, height=80, width=40"
"width=40, height=80, length=10"
What's a quick way to parse a string to get the value of width no matter where it is in the string? Note that it can come at the end of the string or in the beginning/middle followed by a comma. So in the above example, the function should always return 40.

This is the perfect use case for regular expressions.
You want to match width=[0-9]+ but only capture the numeric part, so use a capturing group.
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions.

You can use a regular expression for that.
For example:
parseInt(/width=(\d+)/i.exec(input)[1])
Or, the longer, more readable version:
const input = "length=10, width=40, height=80";
const regex = new RegExp("width=(\\d+)", "i");
const result = regex.exec(input);
const width = parseInt(result[1]);
Alternatively, with a named capturing group:
const input = "length=10, width=40, height=80";
const regex = new RegExp("width=(?<width>\\d+)", "i");
const result = regex.exec(input);
const width = parseInt(result.groups.width);

Related

Regex replace for multiple matches

Trying to figure out a Regex to inject and remove a string (in this case var.par_) at the following locations:
Very Beginning
After ^
After ^OR
Example input string when injecting:
job=developer^language=js^ORlanguage=react^ORlanguageSTARTSWITHjava
Should result in output of
var.par_job=developer^var.par_language=js^ORvar.par_language=react^ORvar.par_languageSTARTSWITHjava
and vice versa when removing:
var.par_language=react^ORvar.par_languageSTARTSWITHjava
should result in
language=react^ORlanguageSTARTSWITHjava
My current feeble attempt was this:
var input = "job=developer^language=js^ORlanguage=react^ORlanguageSTARTSWITHjava";
const replaceToken = "var.par_";
var output = input.replace(/^()?/, replaceToken).replace(/\^()?/g, '^' + replaceToken);
let input = "job=developer^language=js^ORlanguage=react^ORlanguageSTARTSWITHjava";
const replaceToken = "var.par_";
let output = input.replace(/^|\^OR|\^/g, '$&' + replaceToken);
console.log(output)
The regexp /^|\^OR|\^/ matches each of your locations. $& in the replacement gets replaced with the match. So there's no need to use multiple calls to .replace().

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

Extract part of a string which start with a certain word in Javascript

I have the following string
"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,
I need to get string after "ssu":" the Result should be 89c4eef0-3a0d-47ae-a97f-42adafa7cf8f. How do I do it in Javascript but very simple? I am thinking to collect 36 character after "ssu":".
You could build a valid JSON string and parse it and get the wanted property ssu.
var string = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,',
object = JSON.parse(`{${string.slice(0, -1)}}`), // slice for removing the last comma
ssu = object.ssu;
console.log(ssu);
One solution would be to use the following regular expression:
/\"ssu\":\"([\w-]+)\"/
This pattern basically means:
\"ssu\":\" , start searching from the first instance of "ssu":"
([\w-]+) , collect a "group" of one or more alphanumeric characters \w and hypens -
\", look for a " at the end of the group
Using a group allows you to extract a portion of the matched pattern via the String#match method that is of interest to you which in your case is the guid that corresponds to ([\w-]+)
A working example of this would be:
const str = `"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,`
const value = str.match(/\"ssu\":\"([\w-]+)\"/)[1]
console.log(value);
Update: Extract multiple groupings that occour in string
To extract values for multiple occurances of the "ssu" key in your input string, you could use the String#matchAll() method to achieve that as shown:
const str = `"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,"ssu":"value-of-second-ssu","ssu":"value-of-third-ssu"`;
const values =
/* Obtain array of matches for pattern */
[...str.matchAll(/\"ssu\":\"([\w-]+)\"/g)]
/* Extract only the value from pattern group */
.map(([,value]) => value);
console.log(values);
Note that for this to work as expected, the /g flag must be added to the end of the original pattern. Hope that helps!
Use this regExp: /(?!"ssu":")(\w+-)+\w+/
const str = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,';
const re = /(?!"ssu":")(\w+-)+\w+/;
const res = str.match(re)[0];
console.log(res);
You can use regular expressions.
var str = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,'
var minhaRE = new RegExp("[a-z|0-9]*-[a-z|0-9|-]*");
minhaRE.exec(str)
OutPut: Array [ "89c4eef0-3a0d-47ae-a97f-42adafa7cf8f" ]
Looks almost like a JSON string.
So with a small change it can be parsed to an object.
var str = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049, ';
var obj = JSON.parse('{'+str.replace(/[, ]+$/,'')+'}');
console.log(obj.ssu)

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)

Test for specific number of words to match, with a known separator with Regex in Js

i'm trying to check wether a string matches a set of values and they are seperated by a ; It needs to have ; as a separator.
I go this new RegExp(/\b(Segunda|Terça|Quarta|Quinta|Sexta|Sábado|Domingo)\b/, 'gi').test(str)
If i pass:
'Segunda;Terça', true.
'Segundaaa', false.
'Segunda;Terçaa', true.. Why is it true? how can i avoid this?
Thanks in advance.
[EDIT] code:
const WEEK_DAYS_GROUP_REGEX = /\b(Segunda|Terça|Quarta|Quinta|Sexta|Sábado|Domingo)\b/;
const res = new RegExp(WEEK_DAYS_GROUP_REGEX, 'i').test('Segunda;Terçaa');
console.log(res) // gives true
The /\b(Segunda|Terça|Quarta|Quinta|Sexta|Sábado|Domingo)\b/ pattern with gi modifiers matches any of the alternatives as a whole word, it does not guarantee that the whole string consists of these values only, let alone the ; delimiter.
You may use
^(<ALTERNATIONS>)(?:;(<ALTERNATIONS>))*$
See the pattern demo.
In JS, you do not need to use that long pattern, you may build the pattern dynamically:
const strs = ["Segunda;Terça", "Segundaaa", "Segunda;Terçaa"];
const vals = "Segunda|Terça|Quarta|Quinta|Sexta|Sábado|Domingo";
let rx = new RegExp("^(?:" + vals + ")(?:;(?:" + vals + "))*$", "i");
console.log(rx);
for (let s of strs) {
console.log(s,"=>",rx.test(s));
}
Note that the non-capturing groups (?:...) are preferred when there is no need extracting submatches, group values.

Categories

Resources