Javascript - Having trouble using RegExp for a replace - javascript

I'm trying to do a Javascript replace (to remove some words from a string) but I require a variable to be used so I'm using new RegExp() as seen below however I can't figure out why the regular expression isn't replacing the words. When I use the same regex and don't use new RegExp() it works fine.
http://jsfiddle.net/HkEjB/
var string = "foo bar foo bar";
// With RegExp
var replace = "foo";
var regex = new RegExp("\b" + replace + " \b|\b " + replace + "\b|^" + replace + "$", 'igm');
document.write(string.replace(regex, ""));
// Without RegExp
document.write('<br>');
document.write(string.replace(/\bfoo \b|\b foo\b|^foo$/igm, ''));

You need to escape the backslashes: http://jsfiddle.net/HkEjB/1/
var string = "foo bar foo bar";
// With RegExp
var replace = "foo";
var regex = new RegExp("\\b" + replace + " \\b|\\b " + replace + "\\b|^" + replace + "$", 'igm');
document.write(string.replace(regex, ""));

Related

Regex not working on email domain selection properly

var str = "sdhdhh#gmail.com"; // true but coming false
var str1 = "sdhdhh#gmail.co.uk";
var str2 = "sdhdhh#gmail.org";
var str3 = "sdhdhh#gmail.org.uk";
var patt = new RegExp("[a-z0-9._%+-]+#[a-z0-9.-]+?[\.com]?[\.org]?[\.co.uk]?[\.org.uk]$");
console.log( str + " is " + patt.test(str));
console.log( str1 + " is " + patt.test(str1));
console.log( str2 + " is " + patt.test(str2));
console.log( str3 + " is " + patt.test(str3));
Can anyone tell me what is the mistake, my .com example is not working properly
You need
A grouping construct instead of character classes
A regex literal notation so that you do not have to double escape special chars
The ^ anchor at the start of the pattern since you need both ^ and $ to make the pattern match the entire string.
So you need to use
var patt = /^[a-z0-9._%+-]+#[a-z0-9.-]+?(?:\.com|\.org|\.co\.uk|\.org\.uk)$/;
See the regex demo.
If you need to make it case insensitive, add i flag,
var patt = /^[a-z0-9._%+-]+#[a-z0-9.-]+?(?:\.com|\.org|\.co\.uk|\.org\.uk)$/i;

How to rematch the first word or '(' the first word at the beginning

str = "find().nodes() as n3" ==> find
str = "with n1,n2,n3" ===> with
Use string match with the regex pattern ^\w+:
var inputs = ["find().nodes() as n3", "with n1,n2,n3"];
inputs.forEach(x => console.log(x + " => " + x.match(/^\w+/)));

How to apply a regex just for a part of string?

I have a string like this:
var str = "this is test
1. this is test
2. this is test
3. this is test
this is test
1. this test
2. this is test
this is test";
Also I have this regex:
/^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m
This capturing group $1 returns 2 from above string.
Now I have a position number: 65 and I want to apply that regex in this range of the string: [0 - 65]. (So I have to get 3 instead of 2). In general I want to limit that string from first to a specific position and then apply that regex on that range. How can I do that?
The simplest way is to apply it to just that substring:
var match = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(str.substring(0, 65));
// Note ----------------------------------------------------------------^^^^^^^^^^^^^^^^^
Example:
var str = "this is test\n1. this is test\n2. this is test\n3. this is test\nthis is test\n1. this test \n2. this is test\nthis is test";
var match = /^[\s\S]*(?:^|\r?\n)\s*(\d+)(?![\s\S]*(\r?\n){2})/m.exec(str.substring(0, 65));
// Note ----------------------------------------------------------------^^^^^^^^^^^^^^^^^
document.body.innerHTML = match ? "First capture: [" + match[1] + "]" : "(no match)";
Maybe such a build can help (source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec)
var myRe = /ab*/g;
var str = 'abbcdefabh';
var myArray;
while ((myArray = myRe.exec(str)) !== null) {
var msg = 'Found ' + myArray[0] + '. ';
msg += 'Next match starts at ' + myRe.lastIndex;
console.log(msg);
}

Parse complex string with one regular expression

How can I get from this string
genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990
this
genre: [Drama, Comedy],
cast: [Leonardo DiCaprio, Cmelo Hotentot],
year: [1986-1990]
with one regular expression?
This could be done using one regex and overload of replace function with replacer as a second argument. But honestly, I have to use one more replace to get rid of pluses (+) - I replaced them by a space () char:
var str = 'genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990';
str = str.replace(/\+/g, ' ');
var result = str.replace(/(\w+:)(\s?)([\w,\s-]+?)(\s?)(?=\w+:|$)/g, function (m, m1, m2, m3, m4, o) {
return m1 + ' [' + m3.split(',').join(', ') + ']' + (o + m.length != str.length ? ',' : '') + '\n';
});
You could find the full example on jsfiddle.
You will not get them into arrays from the start, but it can be parsed if the order stays the same all the time.
var str = "genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990";
str = str.replace(/\+/g," ");
//Get first groupings
var re = /genre:\s?(.+)\scast:\s?(.+)\syear:\s(.+)/
var parts = str.match(re)
//split to get them into an array
var genre = parts[1].split(",");
var cast = parts[2].split(",");
var years = parts[3];
console.log(genre);
You can't do this using only regular expressions cause you're trying to parse a (tiny) grammar.

Javascript replace using regexp

<input type="text" value="[tabelas][something][oas]" id="allInput">
<script type="text/javascript">
allInput = document.getElementById('allInput');
var nivel = new Array('tabelas', 'produto');
for (var i =0; i < nivel.length ; i++ )
{
alert(" oi => " + allInput.value + " <-- " + nivel[i]) ;
var re = new RegExp("^\[" + nivel[i] + "\]\[.+\].+", "g");
alert(re);
allInput.value = allInput.value.replace(
re, "OLA");
alert(" oi 2 => " + allInput.value + " <-- " + nivel[i]) ;
}
</script>
Basically I whant to replace "something2 in the [tabelas][something][otherfield] by a number of quantity, I have been playing with regexp and had different results from this using .replace(/expression/,xxx ) and new RegExp() .
Best regards and thank you for any help.
You need to double-escape so the escape is seen by the regexp constructor, not the Javascript parser."\[" will result in the string [, "\\[" will result in \[.
Keep in mind that the regexp \[.+\] matches strings like [abc][def]. You probably want \[\w+\] or something similar.
If you construct a RegExp from the new RegExp(...) syntax, then you need two backslashes to escape a character.
new RegExp("^\\[" + nivel[i] + "\\]\\[.+\\].+", "g");

Categories