Regexp: replace character - javascript

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)

Related

I want to remove only one character before particular symbol for example:

I want to remove a specific character, as well as the one before it (in this case # and its preceding character). Example:
"ab#c" -> "ac"
Use a regex and String.replace:
const inp = "ab#c";
const match = /.#/;
const out = inp.replace(match, "");
console.log(out);
Note that this removes any character preceding a '#' in your original string, but only a single occurrence. Add the g flag to match and replace all occurrences, and use [a-zA-Z] to just match letters.
If you want to work the other way (character following, not preceding), and want to replace #c but not \#c, just add that as well:
const inp = "ab\\#c3#cc";
const match = /[^\\]{1}#./;
const out = inp.replace(match, "");
console.log(out);
You can use global regex replace
const inputStr = "ab#c de#f gh#i";
const regxStr = /.#/g;
const outputStr = inputStr.replace(regxStr, "");
console.log(outputStr);

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 when word found

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)

javascript match specific name plus / and characters after it

match a path for a specific word and a / and any characters that follow.
For example.
const str = 'cars/ford';
const isCars = str.match('cars');
What I want to do is make sure it matches cars and has a slash and characters after the / then return true or false.
The characters after cars/... will change so I can't match it excatly. Just need to match any characters along with the /
Would love to use regex not sure what it should be. Looking into how to achieve that via regex tutorials.
var str = "cars/ford";
var patt = new RegExp("^cars/"); //or var patt = /^cars\//
var res = patt.test(str); //true
console.log(res);
https://www.w3schools.com/js/js_regexp.asp
https://www.rexegg.com/regex-quickstart.html
You could use test() that returns true or false.
const str = "cars/ford";
const str2 = "cars/";
var isCars = (str)=>/^cars\/./i.test(str)
console.log(isCars(str));
console.log(isCars(str2));
Here is a quick regex to match "cars/" followed by any characters a-z.
(cars\/[a-z]+)
This will only match lowercase letters, so you can add the i flag to make it case insensitive.
/(cars\/[a-z]+)/i
It is a basic regular expression
var str = "cars/ford"
var result = str.match(/^cars\/(.*)$/)
console.log(result)
^ - start
cars - match exact characters
\/ - match /, the \ escapes it
(.*) - capture group, match anything
$ - end of line
Visualize it: RegExper

Categories