Regex replace for multiple matches - javascript

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().

Related

Get the integer value an attribute in a string in 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);

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)

What will be the efficient way to Replace characters from within braces?

I have the below input
var input = (a-d){12-16},(M-Z){5-8},[#$%!^,12+-,23^!]
I need to remove the comma within the square brackets such that the final output will be
var output = (a-d){12-16},(M-Z){5-8},[#$%!^12+-23^!]
By solution
function test()
{
var input = '(a-d){12-16},(M-Z){5-8},[#$%!^,12+-,23^!]'; //input string
var splitByFirstBracket = input.split("["); //split the input by [ character
//merge the arrays where the second array is replaced by '' for ','
var output = splitByFirstBracket[0] + '[' + splitByFirstBracket[1].replace(/,/g,'');
alert(output);
}
It is providing the output correctly. Is there any better way - I am open both for JavaScript and JQuery.
Thanks in advance
You can use a regular expression replacement. The replacement can be a function, which receives the part of the input that was matched by the regexp, and then it can calculate the replacement. In this case, it would use another replace call to remove the commas.
var input = '(a-d){12-16},(M-Z){5-8},[#$%!^,12+-,23^!]'; //input string
var output = input.replace(/\[.*?\]/g, function(match) {
return match.replace(/,/g, '');
});
console.log(output);

Cannot extract parts of a string

I have a string like this : SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9:.
Using Javascript, I would like to extract the two IDs (which can be different) : 6E5F5E0D-0CA4-426C-A523-134BA33369D7 and C5DD2ADA-E0C4-4971-961F-233789297FE9.
I'm using this regular expression : ^SPList\:(?:[0-9A-Za-z\-]+)\?SPWeb\:(?:[0-9A-Za-z\-]+)\:$.
I expect this expression to extract into two matching groups the two IDs.
By now, my code is :
var input = "SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9:";
var myregex = /^SPList\:(?:[0-9A-Za-z\-]+)\?SPWeb\:(?:[0-9A-Za-z\-]+)\:$/g;
var match = input.match(myregex);
var listId = match[0];
var webId = match[1];
However, this is not working as expected. The first match contains the whole string, and the second match is undefined.
What is the proper way to extract my ID's?
Here is a jsfiddle that illustrate my issue.
This should suit your needs:
var regex = /^SPList:([0-9A-F-]+)[?]SPWeb:([0-9A-F-]+):$/g;
var match = regex.exec(input);
var listId = match[1];
var webId = match[2];
I simply replaced the non-capturing groups of your initial regex by capturing groups, and used regex.exec(input) instead of input.match(regex) to get the captured data. Also, since the IDs seem to be hexadecimal values, I used A-F instead of A-Z.
try this:
var myregex = /[^\:]([0-9A-Z\-]+)[^\?|\:]/g;
var match = input.match(myregex);
alert("listID: " + match[1] + "\n" + "webID: " + match[3]);

How can I remove all characters up to and including the 3rd slash in a string?

I'm having trouble with removing all characters up to and including the 3 third slash in JavaScript. This is my string:
http://blablab/test
The result should be:
test
Does anybody know the correct solution?
To get the last item in a path, you can split the string on / and then pop():
var url = "http://blablab/test";
alert(url.split("/").pop());
//-> "test"
To specify an individual part of a path, split on / and use bracket notation to access the item:
var url = "http://blablab/test/page.php";
alert(url.split("/")[3]);
//-> "test"
Or, if you want everything after the third slash, split(), slice() and join():
var url = "http://blablab/test/page.php";
alert(url.split("/").slice(3).join("/"));
//-> "test/page.php"
var string = 'http://blablab/test'
string = string.replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'')
alert(string)
This is a regular expression. I will explain below
The regex is /[\s\S]*\//
/ is the start of the regex
Where [\s\S] means whitespace or non whitespace (anything), not to be confused with . which does not match line breaks (. is the same as [^\r\n]).
* means that we match anywhere from zero to unlimited number of [\s\S]
\/ Means match a slash character
The last / is the end of the regex
var str = "http://blablab/test";
var index = 0;
for(var i = 0; i < 3; i++){
index = str.indexOf("/",index)+1;
}
str = str.substr(index);
To make it a one liner you could make the following:
str = str.substr(str.indexOf("/",str.indexOf("/",str.indexOf("/")+1)+1)+1);
You can use split to split the string in parts and use slice to return all parts after the third slice.
var str = "http://blablab/test",
arr = str.split("/");
arr = arr.slice(3);
console.log(arr.join("/")); // "test"
// A longer string:
var str = "http://blablab/test/test"; // "test/test";
You could use a regular expression like this one:
'http://blablab/test'.match(/^(?:[^/]*\/){3}(.*)$/);
// -> ['http://blablab/test', 'test]
A string’s match method gives you either an array (of the whole match, in this case the whole input, and of any capture groups (and we want the first capture group)), or null. So, for general use you need to pull out the 1th element of the array, or null if a match wasn’t found:
var input = 'http://blablab/test',
re = /^(?:[^/]*\/){3}(.*)$/,
match = input.match(re),
result = match && match[1]; // With this input, result contains "test"
let str = "http://blablab/test";
let data = new URL(str).pathname.split("/").pop();
console.log(data);

Categories

Resources