Replace Javascript is not working - javascript

I'm trying to replace more than 1 word in same string, with RegExp, but it seems is not working, i tryied some answers here in stackoverflow, but with no result
var _tpl = "time working $times, not now $times"
var reg = "$times"
var regexp = new RegExp(reg, "g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)
console.log(_newTpl)
some advice?

$ is a special character in a regular expression: you must escape it.
var _tpl = "time working $times, not now $times"
var reg = "\\$times"
var regexp = new RegExp(reg, "g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)
console.log(_newTpl)
Note that you need two \s in order to put a single literal \ in the resulting string. If you create the regular expression directly, with regex syntax and not string syntax, only use one \:
const regexp = /\$times/g;

You have to escape regex' special characters before passing them to new RegExp.
var reg = "\\$times"
var _tpl = "time working $times, not now $times"
var reg = "\\$times"
var regexp = new RegExp(reg,"g")
var replaceFor = 1
var _newTpl = _tpl.replace(regexp, replaceFor)
console.log(_newTpl)

Related

Convert URL to string and extract part of to it to a variable [duplicate]

I have this code, it looks alright and is really basic, but i can't make it work:
function checkValid(elem){
var abc = elem.value;
var re = "/[0-9]/";
var match = re.test(abc);
alert(match);
}
It matches 0 and 9, but not 1 to 8, what's wrong here? Thanks.
re is a string, not a RegExp object.
You need to use a regex literal instead of a string literal, like this:
var re = /[0-9]/;
Also, this will return true for any string that contains a number anywhere in the string.
You probably want to change it to
var re = /^[0-9]+$/;
Try removing the double quotes...
var re = /[0-9]/;
Use \d to match a number and make it a regular expresison, not a string:
var abc = elem.value;
var re = /\d/;
var match = re.test(abc);
alert(match);

jQuery Regex from String

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

How to extract string in regex

I have string in this format:
var a="input_[2][invoiceNO]";
I want to extract "invoiceNo" string. I've tried:
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]');
var res = patt.exec(a);
However, I get the following output:
Array [ "[2]", "2" ]
I want to extract only invoiceNo from the string.
Note: Input start can be any string and in place of number 2 it can be any number.
I would check if the [...] before the necessary [InvoiceNo] contains digits and is preceded with _ with this regex:
/_\[\d+\]\s*\[([^\]]+)\]/g
Explanation:
_ - Match underscore
\[\d+\] - Match [1234]-like substring
\s* - Optional spaces
\[([^\]]+)\] - The [some_invoice_123]-like substring
You can even use this regex to find invoice numbers inside larger texts.
The value is in capture group 1 (see m[1] below).
Sample code:
var re = /_\[\d+\]\s*\[([^\]]+)\]/g;
var str = 'input_[2][invoiceNO]';
while ((m = re.exec(str)) !== null) {
alert(m[1]);
}
You can use this regex:
/\[(\w{2,})\]/
and grab captured group #1 from resulting array of String.match function.
var str = 'input_[2][invoiceNO]'
var m = str.match(/\[(\w{2,})\]/);
//=> ["[invoiceNO]", "invoiceNO"]
PS: You can also use negative lookahead to grab same string:
var m = str.match(/\[(\w+)\](?!\[)/);
var a="input_[2][invoiceNO]";
var patt = new RegExp('\[(.*?)\]$');
var res = patt.exec(a);
Try this:
var a="input_[2][invoiceNO]";
var patt = new RegExp(/\]\[(.*)\]/);
var res = patt.exec(a)[1];
console.log(res);
Output:
invoiceNO
You could use something like so: \[([^[]+)\]$. This will extract the content within the last set of brackets. Example available here.
Use the greediness of .*
var a="input_[2][invoiceNO]";
var patt = new RegExp('.*\[(.*?)\]');
var res = patt.exec(a);

Match all entries { * }

I need to match all entries like { * } for string (using Javascript). How can I do it?
Here is an input: "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n";
thanks in advance
Using regular expression maybe:
var r = /{.*?}/g;
var s = "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n";
var matches = s.match(r);
Or if you want to strip those {} in results, you can run an .exec() loop to get a captured data only:
var r = /{(.*?)}/g;
var s = "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n";
var matches = [];
var match = null;
while(match = r.exec(s)) {
matches.push(match[1]);
}
You can try with the following regular expression:
var str = "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n".
var m = str.match(/{.*?}/g);
You'll find all the matches inside m.
Further references: http://www.w3schools.com/jsref/jsref_match.asp
For just the text within the brackets, you should be able to use this pattern:
var pattern = new RegExp("([^{|^}]+)(?=})", "g");
var testString = "#SD#{date};{time};{lat1};{lat2};{lon1};{lon2};{speed};{course};{height};{sats}\r\n";
var bracketTextArray = testString.match(pattern);
The bracketTextArray variable will be an array that contains the following values:
"date", "time", "lat1", "lat2", "lon1", "lon2", "speed", "course", "height", "sats"
The regex matches every occurrence of one or more of any character except { and } (that's this part: ([^{|^}]+)), that are immediately followed by a } character (that's this part: (?=})). The "g" in the RegExp definition makes the pattern "greedy", so that it will find all occurrences.

Match returning null in JavaScript

var regEx = new RegExp("/[0-9]/");
var test = 'TREE'
alert(test.match(regEx));
or
var regEx = new RegExp("/[0-9]/");
var test = '1234'
alert(test.match(regEx));
Why do they return null?
Am i missing something here?
(Ok, the debate mentally drained me last night)
When you are using new RegExp, you don't need the delimiters (/).
var regEx = new RegExp("[0-9]");
var test = '1234'
alert(test.match(regEx));
You only need the slashes if you are using a regex literal (which I prefer using to new RegExp).
var regEx = /[0-9]/;
var test = '1234'
alert(test.match(regEx));
To declare a RegExp:
var patt=new RegExp(pattern,modifiers);
or
var patt=/pattern/modifiers;
So try this:
var regEx = /[0-9]/g;
var test = '1234';
alert(test.match(regEx));

Categories