Regexp: Replace when word found - javascript

I want to replace a word when expression " : " with {{}}.
This is my first try with regexp and i don't know how to do it.
This is what i have :
/:id/user
/auth/:token
This is how i want it to be :
/{{id}}/user
/auth/{{token}}

Use .replace() with a regex as first parameter. In the second one, $1 will be replaced by what is found between the first parenthesis pair in your regex.
const str = "/:id/user/:param/:8d"
const result = str.replace(/:(\w+)/g, '{{$1}}')
console.log(result)

you can match /:id and with replace take off the /: and add {{}}
const url = "/:id/user"
const url2 = "/auth/:token"
const res = url2.replace(/\/:\w*/g, match => `/{{${match.substring(2,match.length)}}}`)
console.log(res)

Related

How to remove part of string that is in parentheses?

I have a string from which I want to remove the last parentheses "(bob)". So far I use this code to return the value within these parentheses:
const str = "Hello my name is (john) (doe) (bob)";
const result = str.split('(').pop().split(')')[0];
console.log(result);
How would I be able to return the string without these last parentheses?
Source: How to remove the last word in a string using JavaScript
Possibly not the cleanest solution, but if you always want to remove the text behind last parentheses, it will work.
var str = "Hello my name is (john) (doe) (bob)";
var lastIndex = str.lastIndexOf("(");
str = str.substring(0, lastIndex);
console.log(str);
You can match the last occurrence of the parentthesis, and replace with capture group 1 that contains all that comea before it:
^(.*)\([^()]*\)
Regex demo
const str = 'Hello my name is (john) (doe) (bob)';
const lastIdxS = str.lastIndexOf('(');
console.log(str.slice(0, lastIdxS).trim());

Getting the content between two characters

So I have this (example) string: 1234VAR239582358X
And I want to get what's in between VAR and X. I can easily replace it using .replace(/VAR.*X/, "replacement");
But, how would I get the /VAR.*X/as a variable?
I think what you are looking for might be
string.match(/VAR(.*)X/)[1]
The brackets around the .* mark a group. Those groups are returned inside the Array that match creates :)
If you want to only replace what's in between "VAR" and "X" it would be
string.replace(/VAR(.*)X/, "VAR" + "replacement" + "X");
Or more generic:
string.replace(/(VAR).*(X)/, "$1replacement$2");
You can try use the RegExp class, new RegExp(`${VAR}.*X`)
You can store it as variable like this,
const pattern = "VAR.*X";
const reg = new RegExp(pattern);
Then use,
.replace(reg, "replacement");
If you
want to get what's in between VAR and X
then using .* would do the job for the given example string.
But note that is will match until the end of the string, and then backtrack to the first occurrence of X it can match, being the last occurrence of the X char in the string and possible match too much.
If you want to match only the digits, you can match 1+ digits in a capture group using VAR(\d+)X
const regex = /VAR(\d+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
Or you can match until the first occurrence of an X char using a negated character class VAR([^\r\nX]+)X
const regex = /VAR([^\r\nX]+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}

Need to replace a string from a long string in javascript

I have a long string
Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
removable_str2 = 'ab#xyz.com;';
I need to have a replaced string which will have
resultant Final string should look like,
cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
I tried with
str3 = Full_str1.replace(new RegExp('(^|\\b)' +removable_str2, 'g'),"");
but it resulted in
cab#xyz.com;c-c.c_ab#xyz.com;
Here a soluce using two separated regex for each case :
the str to remove is at the start of the string
the str to remove is inside or at the end of the string
PS :
I couldn't perform it in one regex, because it would remove an extra ; in case of matching the string to remove inside of the global string.
const originalStr = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;ab#xyz.com;c_ab#xyz.com;';
const toRemove = 'ab#xyz.com;';
const epuredStr = originalStr
.replace(new RegExp(`^${toRemove}`, 'g'), '')
.replace(new RegExp(`;${toRemove}`, 'g'), ';');
console.log(epuredStr);
First, the dynamic part must be escaped, else, . will match any char but a line break char, and will match ab#xyz§com;, too.
Next, you need to match this only at the start of the string or after ;. So, you may use
var Full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
var removable_str2 = 'ab#xyz.com;';
var rx = new RegExp("(^|;)" + removable_str2.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "g");
console.log(Full_str1.replace(rx, "$1"));
// => cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
Replace "g" with "gi" for case insensitive matching.
See the regex demo. Note that (^|;) matches and captures into Group 1 start of string location (empty string) or ; and $1 in the replacement pattern restores this char in the result.
NOTE: If the pattern is known beforehand and you only want to handle ab#xyz.com; pattern, use a regex literal without escaping, Full_str1.replace(/(^|;)ab#xyz\.com;/g, "$1").
i don't find any particular description why you haven't tried like this it will give you desired result cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;
const full_str1 = 'ab#xyz.com;cab#xyz.com;c-ab#xyz.com;c.ab#xyz.com;c_ab#xyz.com;';
const removable_str2 = 'ab#xyz.com;';
const result= full_str1.replace(removable_str2 , "");
console.log(result);

Regexp: replace character

I want to replace a character but nothing happens.
const str = '//id//user/param//test';
const result = str.replace(/[//]/gi, '/');
This is what i get :
//id//user/param//test
This is what i want :
/id/user/param/test
[...] denotes a character group, which matches any one of these characters. So, [//] essentially means "match / or /". Thus [//] is the same as [/].
You don't want a character group:
const str = '//id//user/param//test';
console.log(str.replace(/\/\//gi, '/'));
If you want to match two or more /, use the + or {2,} quantifiers:
/\/{2,}/
/\/\/+/
You can do it also using a regex group /\/+/
const str = '//id//user/param//test';
const result = str.replace(/\/+/g, '/')
console.log(result)

Regular expression extract string

I have a string "#{Name; 11112121#xyz.com}"
I want to write a regular expression that extracts Name and 11112121 from the above string
This is what I tried.
function formatName(text){
var regex = /#\{([^;]+); ([^\}]+)\}/
return text.replace(
regex,
'$1, $2'
);
}
The above gives Name, 11112121#xyz.com. But I want only Name, 11112121
try this
var regex = /#\{([^;]+); ([^\}]+)(#.*)\}/
$1 => Name
$2=> 11112121
Here is the working example
Use match instead, like this:
var regex = /#\{([^;]+);\s+([^#]+)/;
var matches = text.match(regex);
alert(matches[1] + ', ' + matches[2]);
http://jsfiddle.net/rooseve/bM2U6/
If you want to match everything until the # character, you can use
var regex = /#\{([^;]+); ([^#]+)/
If you need to verify that the string also contains a } after that, you can add that to the end:
var regex = /#\{([^;]+); ([^#]+)[^}]*\}/

Categories