regular expression not working properly - javascript

I have problem with JavaScript Regular Expression. I have test it on this website and it's working fine - http://www.pagecolumn.com/tool/regtest.htm .
var str = "Stalowa Wola;Nisko;Rzeszow";
var re = new RegExp("Stalowa Wola[a-zA-Z\W]*Rzeszow", "i");
var myArray = str.match(re);
console.log(myArray);
But when I trying to run this code on my website, it's not working.Console return 'null' and I don't know why. I noticed that when i remove 'Rzeszow' from RegExp it's starts working.

var str = "Stalowa Wola;Nisko;Rzeszow";
var re = new RegExp("Stalowa Wola[a-zA-Z\\W]*Rzeszow", "i");
var myArray = str.match(re);
console.log(myArray);
You need to escape the backslash.
Alternatively use this notation:
var str = "Stalowa Wola;Nisko;Rzeszow";
var re = /Stalowa Wola[a-zA-Z\W]*Rzeszow/i;
var myArray = str.match(re);
console.log(myArray);
The downside is that you must know the structure of the regex before runtime.
http://www.regular-expressions.info/javascript.html

Related

Replace Javascript is not working

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)

simple regex /:[a-z]+/ not working as expected in javascript

Below is a very simple regex code, which works correctly in php and ruby, but not in JS. Plead help me get it working:
var r = /:[a-z]+/
var s = '/a/:b/c/:d'
var m = r.exec(s)
// now m is [":b"]
// it should be [":b", ":d"]
// because that's what i get in ruby and php
Using RegExp.exec() with g (global) modifier is meant to be used inside a loop for getting all matches.
var str = '/a/:b/c/:d'
var re = /:[a-z]+/g
var matches;
while (matches = re.exec(str)) {
// In array form, match is now your next match..
}
You can also use the String.match() method here.
var s = '/a/:b/c/:d',
m = s.match(/:[a-z]+/g);
console.log(m); //=> [ ':b', ':d' ]
var r = /:[a-z]+/g; // i put the g tag here because it needs to match all occurrences
var s = '/a/:b/c/:d';
var m = s.match(r);
console.log(m); // [':b',':d']
I used match because it returns all the matches in an array where as with exec you would have to loop through like the other examples.

matching values stored in variables or array with string javascript regex

Im trying to find a patterns in the sentence for regex matching.. in the code below result contains a string and we are checking if the word apple is present in it.
var patt = /apple/gi;
var newResult = patt.test(result);
I found the above code from a used case.. But i was wondering if i have more than one values and i want to check it in the string result, lets say an array with values var arr=["apple", "orange"] var patt=/arr[0]/gi will not work.. what could be the way in that scenario??
To check multiple entries, you can use the OR operator:
var patt = /apple|orange/gi;
var newResult = patt.test(result);
if you have a variable, you can do the below, IF(!) your key is regexp safe of course (that is, it doesn't contains characters which have meaning in regexp syntax):
var key = "apple";
var patt = new RegExp(key, 'gi');
var newResult = patt.test(result);
Although in this case, you might as well use indexOf:
var key = "apple";
var newResult = result.indexOf(key) > -1;
To use a string for your regex expressions, you need to create the regex using the regex constructor.
var pattern = "apple|orange";
var regex = new RegExp(pattern, "g"); // g is for global match
Read more about it here: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions

Replace a string of the last 7 chars?

This is my code :
​var myStr = "/private_images/last-edit/image-work-med.png";​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
and I'd like to replace the last 7 chars (med.png) with big.png. Or, as you can see, the last occurence after a - split.
How can I do it? I think about regex, but I'm not a champion with them. Tried :
myStr = myStr .replace(/-([^-]*)$/, "big" + '$1');
but it replace the last -, not the last occurence. So the result is /private_images/last-edit/image-workbigmed.png
I'll make a confession: I'm not so great with regexes either.
How about splitting up using split? Less concise, but easier to understand.
var myStr = "/private_images/last-edit/image-work-med.png";​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
var strs = myStr.split('-');
// Change the last element.
strs[strs.length - 1] = "big.png";
// And put back the right string.
myStr = strs.join('-');
You could use a regex, or you could use a few string methods and make your intentions clear.
var idx = myStr.lastIndexOf("-");
var newStr = myStr.substring(0, idx) + "big.png";
Without using RegExp you could use:
var str = "/private_images/last-edit/image-work-med.png"
,replace = 'big.png'
,nwstr = str.slice(0,str.lastIndexOf('-')+1)+replace;
//=> nwstr now "/private_images/last-edit/image-work-big.png"
More 'functional':
var nwstr = function(s){
return s.replace(s.substr(-7),'');}(
'/private_images/last-edit/image-work-med.png'
)+'big.png'
var url = "/private_images/last-edit/image-work-med.png";
var index = url.lastIndexOf('-');
url = url.substring(0, index+1);
var url2 = "big.png";
var output = url.concat(url2); alert(output);
Check this
Just add '-' to your regex and to the replacement string:
myStr = myStr .replace(/-([^-]*)\.png$/, "-big.png");
Or if you want the file extension to be variable:
myStr = myStr .replace(/-([^-]*)\.([a-z]+)$/, "-big.$2");
Why not just use replace:
var myStr = "/private_images/last-edit/image-work-med.png";​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
var newStr = myStr.replace("med.png", "big.png");
According to the requirements specified in your question this would suffice.
If you know it will be a .png file:
var ex = new Regex(#"-\w*.png$");
var myStr = "/private_images/last-edit/image-work-med.png";​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
myStr = ex.Replace(myStr, "-big.png");
It works but if its a jpg it wont...
If you want to use string functions -
var myStr = "/private_images/last-edit/image-work-med.png";
var cleanedupStr = myStr.slice(0, myStr.lastIndexOf("-"));
String.slice

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