I have this string:
var chain = "providerId=12$familyId=123&brandId=1122112$officeId=21&";
I need to do a method that erases a certain word with regular expressions.
Example:
var word = "familyId";
var newChain = deleteParam(chain, word);
console.log(newChain);
Result = "providerId=12$brandId=1122112$officeId=21&";
Delete : familyId=123&
I tried to do the method in the following way, but it does not work:
function deleteParam(chain, word) {
var exp = new RegExp(param, "=[0-9]&");
var str = chain.replace(exp, ""); // Delete
return str
}
Please, I need your help, I can not make this method work, because I do not understand well how to build regular expressions.
Excuse me all, English is not my native language
thank you very much to all.
You can use something like this new RegExp(param + "=\[^&]+")
Here is an example:
var chain = "providerId=12$familyId=123&brandId=1122112$officeId=21&";
var toRemove = "familyId";
var pattern = new RegExp(toRemove + "=[^&]*&");
var newChain = chain.replace(pattern, "");
console.log(newChain);
If you're looking to process a GET request's search parameters is better to use a pattern like this (&|\?)*parameterName=[^&]*
Related
Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);
I have the following Regex that comes from a data Attribute on an HTML Element:
/^$|^[0-9]{2}.[0-9]{4}$/g
When I (manually) do:
/^$|^[0-9]{2}.[0-9]{4}$/g.test('01.2012');
It works and returns true.
When I put the Regex in a Variable like so:
var inputRegex = $(this).attr('data-validation');
And do:
inputRegex.test(input);
I get:
inputRegex.test is not a function.
I know that this is because inputRegex is a String and String does not have a test function, but when I create a RegExp object (new RegExp($(this).attr('data-validation')) it breaks my Regular Expression by escaping:
/\/^$|^[0-9]{2}.[0-9]{4}$\/g/
How can I use the data-attribute value as a Regular Expression? Please note that I cannot do: var regex = new RegExp(string, 'g'); because the Regular Expression(s) come predefined from the attribute.
var pattern = '\d+';
var regExp = new RegExp(pattern, 'g');
'1234dasf13241234'.match(regExp)
is it what you need?
var pattern = $(this).attr('data-validation');;
var regExp = new RegExp(pattern, 'g');
regExp.test(input);
in your case
your problem is that you need to retrieve the regex pattern from a attribute of an element, but it is returning string, and you want the string value to be like inline on your javascript code, like declaring plainly a regex. If this is really what you want to achieve, the closest solution is to use eval function, see updated code below:
var stringreg = "var inputRegex =" + $("#test").attr('data-validation') + ";"
eval(stringreg);
inputRegex.test(input);
This could help
var validation = "/^$|^[0-9]{2}.[0-9]{4}$/g"; //$(this).attr('data-validation')
var startIndex = validation.indexOf('/')+1
var lastIndex = validation.lastIndexOf('/');
var pattern = validation.substring(startIndex,lastIndex);
var options = validation.substring(lastIndex+1);
var regExp = new RegExp(pattern, options);
regExp.test('01.2012');
// true
I have following string var foo = require('foo/bar'); which I want to change to var foo = require('../../foo/bar');.
So far I wrote following code which would do this:
var search = 'foo/bar';
var replace = '../../foo/bar';
var regex = new RegExp('require[(](\"|\')' + search + '(\"|\')[)]', 'g');
var source = 'var foo = require(\'foo/bar\')';
source.replace(regex, 'require(\'' + replace + '\')');
However as you see this is very inefficient. What could I do to make this regex a bit shorter. For example:
only have to replace the path and not to rewrite require with require(\'' + replace + '\')'
make (\"|\') and [(] shorter
anything else?
Best,
Bo
Edit:
I am doing this replacement on complete javascript source files.
Edit2:
What is necessary to change var foobar = require('foo/bar'); to var foobar = require('../../foo/baz/bar') when foo/ and ../../foo/baz/ should be variable?
You can use this code:
var search = 'foo/bar';
var source = "var foo = require('foo/bar')";
var regex = new RegExp('(require)\\((["\'])(' + search + ')\\2\\)', 'g');
var repl = source.replace(regex, "$1('../../$3')");
//=> var foo = require('../../foo/bar')
Here is an alternative :
var str = "var foo = require('foo/bar');";
str = str.split(/(')/);
str.splice(2, 0, '../../');
str = str.join('');
Even simpler :
"var foo = require('foo/bar');".replace(/'([^']+)'/, "'../../$1'")
I wonder if you could do the replacement before wrapping your path inside the var xxx = require() statement.
Optimizing code that starts by undoing what has been done just before seems a bit inefficient.
Besides, it seems you already know the target path (foo/bar in your example), but it is not even necessary to use that.
The regexp here boils down to splitting the string after the opening quote and inserting the ../../ prefix.
You could do that with
source = source.split(/["']/,2).join('"../../')+'");';
The regexp is a constant, so you could put it into a variable to have it compiled once and for all.
That would probably be more efficient than generating and recompiling the regexp from your example each time.
But anyway, I wonder how many such strings you would have to replace to start noticing a performance hit.
I nee to replace all numbers after underline inside a string.
I think that I can use Regex, but I don't know how to use Regex Syntax
See an example of my string:
milton_0
milton_1
If that is the standard format, You can use split()
var str = 'milton_1';
alert(str.split('_')[1]);
You don't need regex for this. The following code in enough
var str = "milton_0";
str = str.substring(0,str.indexOf("_"));
I'm not sure how specific or broad you want to be, but you can try this:
var starter = "milton_1";
var specialVal = "asdf";
var re = /^(milton_)(\d+)$/;
var replaced = starter.replace(re, function (match, p1) {
return p1 + specialVal;
});
console.log(replaced);
http://jsfiddle.net/ne4cD/
This will match a string starting with "milton_" and ending with digits. It replaces any digits after the "_" with the specialVal value.
An example of simply incrementing that number is:
var starter = "milton_1";
var re = /^(milton_)(\d+)$/;
var replaced = starter.replace(re, function (match, p1, p2) {
return p1 + (+p2 + 1);
});
console.log(replaced);
http://jsfiddle.net/ne4cD/2/
UPDATE:
If the "milton" part isn't static, then you're really only targeting the "_" with digits after it. So something like this:
var starter = "asdfkjlasdfjksadf_1";
var specialVal = "asdf";
var re = /(_)(\d+)/g;
var replaced = starter.replace(re, function (match, p1) {
return p1 + specialVal;
});
console.log(replaced);
http://jsfiddle.net/ne4cD/3/
And maybe a little better to see: http://jsfiddle.net/ne4cD/4/
First of all you need them as list for handling easily.
var listOfStrings = yourStringObject('whateverYourCharacterUnderEachWord').ToList<string>();
After that you need to get rid of number for each string in the list and add what you want.
foreach(string word in listOfStrings){
word = word.Substring(0,word.IndexOf('_')+1);
word = word + "characterThatYouWantToAddHere"
}
I have a RegExp that I would like to make dynamic and create in a string. I want to change this:
var result:Object = value.match(/John\/(.*?) /);
to this:
var firstName:String = "John";
var result:Object = value.match(firstName + "\/(.*?) "); // this doesn't work
I'm using ActionScript but I think what would work in JavaScript would work as well here.
In Javascript you can create a new instance of the RegExp class:
var firstName:String = "John";
var result:Object = value.match(new RegExp(firstName + "\/(.*?) "));
When you use value.match(firstName + "\/(.*?) "); the first parameter to the match function is a string, but it should be a regular expression object.