How to replace a string using regexp in JavaScript - javascript

I want to filter a given string and replace some common words from a given string:
const str ='api/knwl/tests/products';
const str1 = 'api/users';
const str2 = 'api/tests/providers';
I want to filter the words 'api', 'knwl' or 'tests' from a given strings.
I tried somthing with regexp:
/(?!(tests|api|knwl))/g
But it doesn't work. How can I fix this issue? I'm not expert on regexp.

Regex - /(tests|api|knwl)/g;
const str ='api/knwl/tests/products';
const str1 = 'api/users';
const str2 = 'api/tests/providers';
const filterRegex = str.replace(/(tests|api|knwl)/g,''); // replace all occurence of strings (tests,api,knwl) to empty.

Related

How do i use a Regex separator that looks like a named group?

I am splitting a string that contains substrings of this form:
"<at>foo bar</at>"
using this construct:
tokens = command.trim().split( /,\s+|,|\s+|(?=<at>)|(?=<\/at>)/ )
However, the result is an array:
["<at>foo", "bar", "</at>"]
How do I modify the regex to produce?:
["<at>", "foo", "bar", "</at>"]
Thanks in advance.
Instead of using split, you might match the parts
<\/?at>|[^<>\s]+
Regex demo
const regex = /<\/?at>|[^<>\s]+/g;
console.log(`<at>foo bar</at>`.match(regex));
Using split, the pattern could be
,\s*|\s+|(?<=<at>)|(?=<\/at>)
const regex = /,\s*|\s+|(?<=<at>)|(?=<\/at>)/g;
console.log(`<at>foo bar</at>`.split(regex))
Nice answer by #The fourth bird
Another way could be splitting only the string between the tags:
const chars = "<at>foo bar</at>";
const tags = /<\/?at>/g;
const tokens = chars.replace(tags, "").split(/\s/);
const result = ["<at>", ...tokens, "</at>"]
console.log(result)

Javascript regex to parse string

I have the following strings :
id,square,vegetable.garden:id<>cell:gardenId
id,square,vegetable.garden:id<>cell:gardenId?id=10
id,square,vegetable.garden:id<>cell:gardenId#toto
id,square,vegetable.garden:id<>cell:gardenId^titi
id,square,vegetable.garden:id<>cell:gardenId?id=10#toto^titi
id,square,vegetable.garden:id<>cell:gardenId#toto^titi
With JS I want to match all parameters. I have the regex
/(\S*)\.(\S*)([\?#\^])(\S*)([\?#\^])(\S*)([\?#\^])(\S*)/g
But this regex matching and catching parameters for the 5th string only. Do you have an solution to match all the strings ?
Thanks for your help.
Sorry if it's not clear.
I have this
id,square,vegetable.garden:id<>cell:gardenId?id=10#toto^titi
And I want to split parameters to have :
group1 = id,square,vegetable
group2 = garden:id<>cell:gardenId
group3 = ?
group4 = id=10
group5 = #
group6 = toto
group7 = ^
group8 = titi
The previous regex working. But for other string this regex not working because I can have differents order for #, ^ or ? separator and they can be optionals.
Online RegEx with examples here.
It's more clear ?
Assuming that you only have 3 pieces maximum that it can extend to:
Here's a regex that should work for you:
([^\s.]*)\.([^?#^\s]+)(?:([?#^])([^?\s#^]+))?(?:([?#^])([^?\s#^]+))?(?:([?#^])([^?\s#^]+))?
It matches all the example strings that you gave and seems to match fairly quickly as well.
The repeating bit (?:([?#^])([^?\s#^]+))?matches optionally if there is a ?, #, or ^ followed by all the characters that aren't one of them or a whitespace.
https://regex101.com/r/MRzMdK/2
It's a little unclear what you want to do, but you could try something like this to use a regex to see if a string contains another string:
const str1 = 'id,square,vegetable.garden:id<>cell:gardenId'
const str2 = 'id,square,vegetable.garden:id<>cell:gardenId?id=10'
const str3 = 'id,square,vegetable.garden:id<>cell:gardenId#toto'
const str4 = 'id,square,vegetable.garden:id<>cell:gardenId^titi'
const str5 = 'id,square,vegetable.garden:id<>cell:gardenId?id=10#toto^titi'
const str6 = 'id,square,vegetable.garden:id<>cell:gardenId#toto^titi'
const regex = new RegExp(str1, "ig")
const res = str2.match(regex)
console.log(res)

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)

How to convert regex string to regex expression? [duplicate]

So I have a RegExp regex = /asd/
I am storing it as a as a key in my key-val store system.
So I say str = String(regex) which returns "/asd/".
Now I need to convert that string back to a RegExp.
So I try: RegExp(str) and I see /\/asd\//
this is not what I want. It is not the same as /asd/
Should I just remove the first and last characters from the string before converting it to regex? That would get me the desired result in this situation, but wouldn't necessarily work if the RegExp had modifiers like /i or /g
Is there a better way to do this?
If you don't need to store the modifiers, you can use Regexp#source to get the string value, and then convert back using the RegExp constructor.
var regex = /abc/g;
var str = regex.source; // "abc"
var restoreRegex = new RegExp(str, "g");
If you do need to store the modifiers, use a regex to parse the regex:
var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var parts = /\/(.*)\/(.*)/.exec(str);
var restoredRegex = new RegExp(parts[1], parts[2]);
This will work even if the pattern has a / in it, because .* is greedy, and will advance to the last / in the string.
If performance is a concern, use normal string manipulation using String#lastIndexOf:
var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var lastSlash = str.lastIndexOf("/");
var restoredRegex = new RegExp(str.slice(1, lastSlash), str.slice(lastSlash + 1));
const regex = /asd/gi;
converting RegExp to String
const obj = {flags: regex.flags, source: regex.source};
const string = JSON.stringify(obj);
then back to RegExp
const obj2 = JSON.parse(string);
const regex2 = new RegExp(obj2.source, obj2.flags);
Requires ES6+.
You can use the following before storage of your regex literal:
(new RegExp(regex)).source
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source
Example:
regex = /asd/
string = (new RegExp(regex)).source
// string is now "asd"
regex = RegExp(string)
// regex has the original value /asd/
let rx = RegExp.apply(RegExp, str.match(/\/(.*)\/(.*)/).slice(1));
A modified version of #PegasusEpsilon answer
StackOverflow saves the day again, thanks #4castle! I wanted to store some regex rules in a JS file, and some in a DB, combine them into an array of objects like so:
module.exports = {
[SETTINGS.PRODUCTION_ENV]: [
{
"key": /<meta name="generator"[\s\S]*?>/gmi,
"value": "",
"regex": true
},
...
]
}
Then, loop through each environment's objects and apply it to a string of text. This is for a node/lambda project, so I wanted to use ES6. I used #4castle's code, with some destructuring, and I ended up with this:
let content = body;
const regexString = replacement.key.toString();
const regexParts = /\/(.*)\/(.*)/.exec(regexString);
const {1: source, 2: flags} = regexParts;
const regex = new RegExp(source, flags);
content = content.replace(regex, replacement.value);
return content;
Works a treat!

Split string and get array using regExp in javascript/node js

I am writing js code to get array of elements after splitting using regular expression.
var data = "ABCXYZ88";
var regexp = "([A-Z]{3})([A-Z]{3}d{2})";
console.log(data.split(regexp));
It returns
[ 'ABCXYZ88' ]
But I am expecting something like
['ABC','XYZ','88']
Any thoughts?
I fixed your regex, then matched it against your string and extracted the relevant capturing groups:
var regex = /([A-Z]{3})([A-Z]{3})(\d{2})/g;
var str = 'ABCXYZ88';
let m = regex.exec(str);
if (m !== null) {
console.log(m.slice(1)); // prints ["ABC", "XYZ", "88"]
}
In your case, I don't think you can split using a regex as you were trying, as there don't seem to be any delimiting characters to match against. For this to work, you'd have to have a string like 'ABC|XYZ|88'; then you could do 'ABC|XYZ|88'.split(/\|/g). (Of course, you wouldn't use a regex for such a simple case.)
Your regexp is not a RegExp object but a string.
Your capturing groups are not correct.
String.prototype.split() is not the function you need. What split() does:
var myString = 'Hello World. How are you doing?';
var splits = myString.split(' ', 3);
console.log(splits); // ["Hello", "World.", "How"]
What you need:
var data = 'ABCXYZ88';
var regexp = /^([A-Z]{3})([A-Z]{3})(\d{2})$/;
var match = data.match(regexp);
console.log(match.slice(1)); // ["ABC", "XYZ", "88"]
Try this. I hope this is what you are looking for.
var reg = data.match(/^([A-Z]{3})([A-Z]{3})(\d{2})$/).slice(1);
https://jsfiddle.net/m5pgpkje/1/

Categories

Resources