Javascript RegExp help - javascript

I am trying to replace a certain text in Javascript.
newexp is a variable.
numexp is a variable
replacenamestring = new RegExp('Memberresumeexp\[1\]',"ig");
newexp = newexp.replace(replacenamestring,'Memberresumeexp[' + numexp + ']');
The above replace is not working.
How ever this works.
newexp = newexp.replace(/Memberresumeexp\[1\]/ig,'Memberresumeexp[' + numexp + ']');
Not able to figure out why?

Your first line creates a Javascript string, then parses the string as a regex.
Javascript string literals use \ as an escape character, so the \s are not part of the string value. Therefore, the [ and ] in your regex aren't escaped, so it's creating a character class.
You need to escape the \s by writing \\.

Here's a working example for you with one BIG caveat -- I changed "[1]" to "[\d+]" just in case you needed this for more cases of Memberresumeexp[<any number>]. Also, I hardcoded numexp, because I had not seen how it was initialized.
var replacenamestring = new RegExp('Memberresumeexp\\[\\d+\\]',"ig");
var newexp = "asdfasdflkj;lakwjef Memberresumeexp[1] asdfasdfasdf\nqwerqwerwer Memberresumeexp[2] qwerqwerwqerewr\n";
var numexp = 123;
if(replacenamestring.test(newexp))
{
newexp = newexp.replace(replacenamestring,'Memberresumeexp[' + numexp + ']');
}

It's a simple lexical syntax issue. In the first case, you're creating the RegExp object with the constructor, which starts from a string constant. Well, string constants have their own syntactic quirks, and in particular those backslashes in the string will be interpreted during its own parsing. By the time the RegExp constructor is called, those are gone.
The "native" RegExp syntax has its own quoting rules, which are such that the "[" and "]" portions of the pattern are correctly interpreted when you use that syntax.

Related

How to include a variable and exclude numbers[0-9] and letters[a-zA-Z] in RegExp?

I have a code that generates a random letter based on the word and I have tried to create a RegExp code to turn all the letters from the word to '_' except the randomly generated letter from the word.
const word = "Apple is tasty"
const randomCharacter = word[Math.floor(Math.random() * word.length)]
regex = new RegExp(/[^${randomCharacter}&\/\\#,+()$~%.'":;*?<>{}\s]/gi)
hint = word.replace(regex,'_')
I want to change all the letters to '_' except the randomly generated word. The above code for some reason does not work and shows the result: A___e __ ta_t_ and I'm not able to figure out what to do.
The final result I want is something like this: A____ __ _a___
Is there a way with regex to change all the alphabets and numbers '/[^a-zA-Z0-9]/g' to '_' except the randomly generated letter?
I'm listing all the expressions I want to include on my above code because I'm not able to figure out a way to do include and exclude at the same time using the variable with regex.
You can't do string interpolation inside of a RegExp literal (/.../). Meaning your placeholder ${randomCharacter} will not evaluate to its value in the template, but is instead interpreted literally as the string "${randomCharacter}".
If you want to use template literals, initialize your regex variable with a RegExp constructor instead, like:
const regex = new RegExp(`[^${randomCharacter}&\\/\\\#,+()$~%.'":;*?<>{}\\s]`, "gi");
See the MDN RegExp documentation for an explanation on the differences between the literal notation and constructor function, most notably:
The constructor of the regular expression object [...] results in runtime compilation of the regular expression. Use the constructor function when [...] you don't know the pattern and obtain it from another source, such as user input.
/(?:[^A\s])/
test it on regex101
just replace A in [^A\s] with you character that you want to ommit from replacement
demo:
const word = "Apple is tasty";
const randomCharacter = 'a';//word[Math.floor(Math.random() * word.length)];
regex = new RegExp('(?:[^' + randomCharacter + '\\s])', 'gi');
hint = word.replaceAll(regex, '_');
console.log(hint)

How to convert string from PHP to javascript regular expression?

This is my string converted into javascript object.
{"text" : "Must consist of alphabetical characters and spaces only", regexp:"/^[a-z\\s]+$/i"}
I need regexp to use it for validation but it won’t work because of the double quotes and \s escape sequence.
To make it work the value of regexp must be {"text" : "Must consist of alphabetical characters and spaces only", regexp : /^[a-z\s]+$/i}.
I also used this new RegExp(object.regexp) and any other way I can possibly think but with no luck at all.
Any help is appreciated!
Try split-ing out the part that you want, before putting it into the new RegExp constructor:
var regexVariable = new RegExp(object.regexp.split("/")[1]);
That will trim off the string representation of the regex "boundaries", as well as the "i" flag, and leave you with just the "guts" of the regex.
Pushing the result of that to the console results in the following regex: /^[a-z\s]+$/
Edit:
Not sure if you want to "read" the case insensitivity from the value in the object or not, but, if you do, you can expand the use of the split a little more to get any flags included automatically:
var aRegexParts = object.regexp.split("/");
var regexVariable = new RegExp(aRegexParts[1], aRegexParts[2]);
Logging that in the console results in the first regex that I posted, but with the addition of the "i" flag: /^[a-z\s]+$/i
Borrowing the example #RoryMcCrossan made, you can use a regular expression to parse your regular expression.
var object = {
"text": "Must consist of alphabetical characters and spaces only",
"regexp": "/^[a-z\\s]+$/i"
}
// parse out the main regex and any additional flags.
var extracted_regex = object.regexp.match(/\/(.*?)\/([ig]+)?/);
var re = new RegExp(extracted_regex[1], extracted_regex[2]);
// don't use document.write in production! this is just so that it's
// easier to see the values in stackoverflow's editor.
document.write('<b>regular expression:</b> ' + re + '<br>');
document.write('<b>string:</b> ' + object.text + '<br>');
document.write('<b>evaluation:</b> ' + re.test(object.text));
not used regex in Java but the regular expression itself should look something like :
"^([aA-zZ] | \s)*$"
If Java uses regular expression as I am used to them [a-z] will only capture lowercase characters
Hope this helps even if it's just a little (would add this as a comment instead of answer but need 50 rep)

Ignoring whitespace in Javascript regular expression patterns?

From my research it looks like Javascript's regular expressions don't have any built-in equivalent to Perl's /x modifier, or .NET's RegexOptions.IgnorePatternWhitespace modifier. These are very useful as they can make a complex regex much easier to read. Firstly, have I missed something and is there a Javascript built-in equivalent to these? Secondly, if there isn't, does anyone know of a good jQuery plugin that will implement this functionality? It's a shame to have to compress my complex regex into one line because of Javascript's apparent regex limitations.
If I understand you correctly you want to add white space that isn't part of the regexp?
As far as I know it isn't possible with literal regexp.
Example:
var a = /^[\d]+$/
You can break up the regexp in several lines like this:
var a = RegExp(
"^" +
"[\\d]+" + // This is a comment
"$"
);
Notice that since it is now a normal string, you have to escape \ with \\
Or if you have a complex one:
var digit_8 = "[0-9]{8}";
var alpha_4 = "[A-Za-z]{4}";
var a = RegExp(
digit_8 +
alpha_4 + // Optional comment
digit_8
);
Update: Using a temporary array to concatenate the regular expression:
var digit_8 = "[0-9]{8}";
var alpha_4 = "[A-Za-z]{4}";
var a = RegExp([
digit_8,
alpha_4, // Optional comment
digit_8,
"[0-9A-F]" // Another comment to a string
].join(""));
Unfortunately there isn't such option in ES5, and I suspect it's unlikely to ever be in RegExp literals, because they're already very hard to parse and line breaks would make them even more ambiguous.
If you want easy escaping and syntax highlighting of RegExp literals, you can join them by taking advantage of the source property. It's not perfect, but IMHO less bad than falling all the way back to strings:
new RegExp(
/foo/.source +
/[\d+]/.source +
/bar/.source
);
In ES6 you can create your own template string:
regexp`
foo
[\d+]
bar
`;
function regexp(parts) {
// I'm ignoring support for ${} placeholders for brevity,
// but full implementation should escape them.
// Note that `.raw` allows use of \d instead of \\d.
return new RegExp(parts.raw.join('').replace(/\s+/g,''));
}

Why do you need the + between variables in javascript?

Why does this line work
$('#body-image').css("background-image", 'url('+ backgroundimage +')');
but not this one
$('#body-image').css("background-image", 'url('backgroundimage')');
or this one
$('#body-image').css("background-image", 'url(backgroundimage)');
backgroundimage is a JavaScript variable. The concatenation operator in JavaScript is +, so to put a string together with a variable, you do 'some string ' + someVariable. Without the +'s, JavaScript wouldn't know what to do with your variable (and in your third example, wouldn't even know that it was a variable).
You need to concat the string with the variable backgroundimage. So you use "+" for this.
That's why this doesn't work.
$('#body-image').css("background-image", 'url('backgroundimage')');
And the secont doesn't work because there is no image called 'backgroundimage'.
$('#body-image').css("background-image", 'url(backgroundimage)');
Because you are building a string. You are missing the line where backgroundimage gets a value:
var backgroundimage = "someimage.gif";
$('#body-image').css("background-image", 'url('+ backgroundimage +')');
becomes:
$('#body-image').css("background-image", 'url(someimage.gif)');
it's concatenating the string.
let's say backgroundimage is 'foo.jpg, then
'url('+backgroundimage+')' = 'url(foo.jpg)'
In JavaScript, a string literal (i.e., "I am a string") is actually treated like a String object (though, strictly speaking, it isn't - see the MDC documentation - but we can ignore the difference at this level). The following two lines are equivalent:
var letters = "ABC", numbers = "123";
var letters = new String("ABC"), numbers = new String("123");
Strings are concatenated using either the + operator or the String.concat method, either of which join 2 or more strings in a left-to-right order and return the result. So in order to get "ABC123", we can do any of the following:
"ABC" + "123"
"ABC" + numbers
letters + "123"
letters + numbers
"ABC".concat("123")
"ABC".concat(numbers)
letters.concat("123")
letters.concat(numbers)
but not:
letters"123"
"ABC"numbers
lettersnumbers
"lettersnumbers"
which are all, effectively, the same thing that you were trying to do in your examples.

How to replace multiple strings with replace() in Javascript

I'm guessing this is a simple problem, but I'm just learning...
I have this:
var location = (jQuery.url.attr("host"))+(jQuery.url.attr("path"));
locationClean = location.replace('/',' ');
locationArray = locationClean.split(" ");
console.log(location);
console.log(locationClean);
console.log(locationArray);
And here is what I am getting in Firebug:
stormink.net/discussed/the-ideas-behind-my-redesign
stormink.net discussed/the-ideas-behind-my-redesign
["stormink.net", "discussed/the-ideas-behind-my-redesign"]
So for some reason, the replace is only happening once? Do I need to use Regex instead with "/g" to make it repeat? And if so, how would I specifiy a '/' in Regex? (I understand very little of how to use Regex).
Thanks all.
Use a pattern instead of a string, which you can use with the "global" modifier
locationClean = location.replace(/\//g,' ');
The replace method only replaces the first occurance when you use a string as the first parameter. You have to use a regular expression to replace all occurances:
locationClean = location.replace(/\//g,' ');
(As the slash characters are used to delimit the regular expression literal, you need to escape the slash inside the excpression with a backslash.)
Still, why are you not just splitting on the '/' character instead?
You could directly split using the / character as the separator:
var loc = location.host + location.pathname, // loc variable used for tesing
locationArray = loc.split("/");
This can be fixed from your javascript.
SYNTAX
stringObject.replace(findstring,newstring)
findstring: Required. Specifies a string value to find. To perform a global search add a 'g' flag to this parameter and to perform a case-insensitive search add an 'i' flag.
newstring: Required. Specifies the string to replace the found value from findstring
Here's what ur code shud look like:
locationClean = location.replace(new RegExp('/','g'),' ');
locationArray = locationClean.split(" ");
njoi'

Categories

Resources