This question already has an answer here:
Javascript Regular Expression not matching
(1 answer)
Closed 7 years ago.
I'm trying to replace all occurences of {0}, {1}, {2}, etc in a string with Javascript.
Example string:
var str = "Hello, my name is {0} and I'm {1} years.";
I'm tried the following to construct the regexp:
var regex1 = new RegExp("{" + i + "}", "g")
var regex2 = new RegExp("\{" + i + "\}", "g")
Both attempts throws the error:
Invalid regular expression: /{0}/: Nothing to repeat
I use replace like this:
str.replace(regex, "Inserted string");
Found all kinds of StackOverflow posts with different solutions, but not quite to solve my case.
The string literal "\{" results in the string "{". If you need a backslash in there, you need to escape it:
"\\{"
This will results in the regex \{..\}, which is the correct regex syntax.
Having said that, your approach is more than weird. Using a regex you should do something like this:
var substitues = ['foo', 'bar'];
str = str.replace(/\{(\d+)\}/, function (match, num) {
return substitutes[num];
});
In other words, don't dynamically construct a regex for each value; do one regex which matches all values and lets you substitute them as needed.
Related
This question already has an answer here:
Part of String Case Insensitive in JavaScript Regex (?i) option not working
(1 answer)
Closed 3 years ago.
I'd like to perform a case insensitive regex match for only some of the words in regex string. For example I have this search string:
var str = "one two three four five";
I'd like to inspect it at least one of the values in /One|TWO/ is present in string. For some values I am interested in case-sensitive match, for others in case-insensitive. So, for example:
str.match(/One|TWO/);
Search for One should be performed in case-insensitive manner, and search for TWO should be case-sensitive.
Is this variable case sensitive match possible with Javascript Regex engine? Appending i as in str.match(/One|TWO/i); causes a case-insensitive search for the whole regex string and not just parts of it.
Usually, in regex, there are those useful things:
(?i) : starts case-insensitive mode
(?-i) : turns off case-insensitive mode
So, you would be able to write (?i)One(?-i)TWO. That will make One case-insensitive and TWO case-sensitive.
However, they are not supported in JavaScript.
Now, since you said that you will know your regex search string at runtime; then, you have two options:
Create 2 regex search strings, one with \i and one without \i
var str = "one two three four five";
var insens_re = RegExp("One", "ig");
var sens_re = RegExp("TWO", "g");
console.log(insens_re);
console.log(sens_re);
var a = str.match(insens_re) || [];
var b = str.match(sens_re) || [];
console.log("Matches : ", a.concat(b));
Use the function written below in order to convert any case-insensitive word to a more complex regex search string
function makeInsensitive(s) {
var a = s.toUpperCase().split("");
var b = s.toLowerCase().split("");
return a.map((c, i) => "[" + b[i] + c + "]").join("");
}
var str = "one two three four five";
var re = RegExp(makeInsensitive("One") + "|TWO", "g");
console.log(re);
console.log("Matches : ", str.match(re));
This question already has answers here:
Difference between matches() and find() in Java Regex
(5 answers)
Closed 3 years ago.
Same regex, different results;
Java
String regex = "Windows(?=95|98|NT|2000)";
String str = "Windows2000";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
System.out.println(m.matches()); // print false
JavaScript
var value = "Windows2000";
var reg = /Windows(?=95|98|NT|2000)/;
console.info(reg.test(value)); // print true
I can't understand why this is the case?
From the documentation for Java's Matcher#matches() method:
Attempts to match the entire region against the pattern.
The matcher API is trying to apply your pattern against the entire input. This fails, because the RHS portion is a zero width positive lookahead. So, it can match Windows, but the 2000 portion is not matched.
A better version of your Java code, to show that it isn't really "broken," would be this:
String regex = "Windows(?=95|98|NT|2000)";
String str = "Windows2000";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println(m.group()); // prints "Windows"
}
Now we see Windows being printed, which is the actual content which was matched.
This question already has answers here:
Regular Expression to get a string between parentheses in Javascript
(10 answers)
Closed 4 years ago.
I have string like this:
var str = "Hello (World) I'm Newbie";
how to get World from string above using RegExp?, I'm sorry I don't understand about regex.
Thank's
Rather than using a regex - use .split()...Note the escaped characters in the splits. The first split gives "World) I'm Newbie" and the second gives "World".
var str = "Hello (World) I'm Newbie";
var strContent = str.split('\(')[1].split('\)')[0];
console.log(strContent); // gives "World"
Assuming that there will be atleast one such word, you can do it using String#match. The following example matches the words between parentheses.
console.log(
"Hello (World) I'm Newbie"
.match(/\(\w+\)/g)
.map(match => match.slice(1, -1))
)
This might help you for your regex
\w match whole world
+ plus with another regex
[] starts group
^ except
(World) matching word
var str = "Hello (World) I'm Newbie";
var exactword=str.replace(/\w+[^(World)]/g,'')
var filtered = str.replace(/(World)/g,'')
alert(exactword)
alert(filtered)
This question already has answers here:
Parse query string in JavaScript [duplicate]
(11 answers)
Closed 8 years ago.
So let's say I have this HTML link.
<a id="avId" href="http://www.whatever.com/user=74853380">Link</a>
And I have this JavaScript
av = document.getElementById('avId').getAttribute('href')
Which returns:
"http://www.whatever.com/user=74853380"
How do I extract 74853380 specifically from the resulting string?
There are a couple ways you could do this.
1.) Using substr and indexOf to extract it
var str = "www.something.com/user=123123123";
str.substr(str.indexOf('=') + 1, str.length);
2.) Using regex
var str = var str = "www.something.com/user=123123123";
// You can make this more specific for your query string, hence the '=' and group
str.match(/=(\d+)/)[1];
You could also split on the = character and take the second value in the resulting array. Your best bet is probably regex since it is much more robust. Splitting on a character or using substr and indexOf is likely to fail if your query string becomes more complex. Regex can also capture multiple groups if you need it to.
You can use regular expression:
var exp = /\d+/;
var str = "http://www.whatever.com/user=74853380";
console.log(str.match(exp));
Explanation:
/\d+/ - means "one or more digits"
Another case when you need find more than one number
"http://www.whatever.com/user=74853380/question/123123123"
You can use g flag.
var exp = /\d+/g;
var str = "http://www.whatever.com/user=74853380/question/123123123";
console.log(str.match(exp));
You can play with regular expressions
Well, you could split() it for a one liner answer.
var x = parseInt(av.split("=")[1],10); //convert to int if needed
This question already has answers here:
JavaScript regex pattern concatenate with variable
(3 answers)
Closed 7 years ago.
I have a regex to check if a string contains a specific word. It works as expected:
/\bword\b/.test('a long text with the desired word amongst others'); // true
/\bamong\b/.test('a long text with the desired word amongst others'); // false
But i need the word which is about to be checked in a variable. Using new RegExp does not work properly, it always returns false:
var myString = 'a long text with the desired word amongst others';
var myWord = 'word';
new RegExp('\b' + myWord + '\b').test(myString); // false
myWord = "among";
new RegExp('\b' + myWord + '\b').test(myString); // false
What is wrong here?
var myWord = 'word';
new RegExp('\\b' + myWord + '\\b')
You need to double escape the \ when building a regex from a string.
This is because \ begins an escape sequence in a string literal, so it never makes it to the regex. By doing \\, you're including a literal '\' character in the string, which makes the regex /\bword\b/.