I have a problem with regular expression:
var regex = new RegExp('(^|\\s)' + clsName + '(\\s|$)');
What does (^|\\s) mean? Isn't it equal to (^|\s), what does (^|) mean?
Am I right, it means that the string should start with any letter or white space? I tried to test with browser and console.log but still can't get any solution.
In all tutorials \s is used to be a space pattern not \\s.
Ok i got it, the problem was:
When using the RegExp constructor: for each backslash in your regular expression, you have to type \\ in the RegExp constructor. (In JavaScript strings, \\ represents a single backslash!) For example, the following regular expressions match all leading and trailing whitespaces (\s); note that \\s is passed as part of the first argument of the RegExp constructor:
re = /^\s+|\s+$/g
re = new RegExp('^\\s+|\\s+$','g')
(^|\\s) means: Start of the string (^) OR (|) a space \\s.
If clsName is "abc", for example, it builds the pattern (^|\\s)abc(\\s|$). That searches for "abc" at the start, middle, or end of the string, and it may be surrounded by spaces, so these are valid:
"abc"
"abc x"
"x abc"
"x abc y"
Note that here you are using a string to build a RegExp. JavaScript ignores escape characters it doesn't know - '\s' would be the same as 's', which isn't right.
Another option is to use word boundaries, but might fail on some case (for example, searching for btn would match for btn-primary):
var regex = new RegExp('\\b' + clsName + '\\b');
I'd also warn that clsName might contain regex meta-characters, so you may want to escape it.
Why not just split the string on " "?
var string = 'abc defh ij klm';
var elements = string.split(' ');
var clsName = 'abc';
elements.filter(function (el) {
return el === clsName;
});
No need for a RegEx like the one you posted.
Related
I am stuck with creating regex such that if the word is preceded or ended by special character more than one regex on each side regex 'exec' method should throw null. Only if word is wrap with exactly one bracket on each side 'exec' method should give result Below is the regular expression I have come up with.
If the string is like "(test)" or then only regex.exec should have values for other combination such as "((test))" OR "((test)" OR "(test))" it should be null. Below code is not throwing null which it should. Please suggest.
var w1 = "\(test\)";
alert(new RegExp('(^|[' + '\(\)' + '])(' + w1 + ')(?=[' + '\(\)' + ']|$)', 'g').exec("this is ((test))"))
If you have a list of words and want to filter them, you can do the following.
string.split(' ').filter(function(word) {
return !(/^[!##$%^&*()]{2,}.+/).test(word) || !(/[!##$%^&*()]{2,}$).test(word)
});
The split() function splits a string at a space character and returns an array of words, which we can then filter.
To keep the valid words, we will test two regex expressions to see if the word starts or ends with 2 or more special characters respectively.
RegEx Breakdown
^ - Expression starts with the following
[] - A single character in the block
!##$%^&*() - These are the special characters I used. Replace them with the ones you want.
{2,} - Matches 2 or more of the preceeding characters
.+ - Matches 1 or more of any character
$ - Expression ends with the following
To use the exec function this way do this
!(/^[!##$%^&*()]{2,}.+/).exec(string) || !(/[!##$%^&*()]{2,}$).exec(string)
If I understand correctly, you are looking for any string which contains (test), anywhere in it, and exactly that, right?
In that case, what you probably need is the following:
var regExp = /.*[^)]\(test\)[^)].*/;
alert(regExp.exec("this is ((test))")); // → null
alert(regExp.exec("this is (test))" )); // → null
alert(regExp.exec("this is ((test)" )); // → null
alert(regExp.exec("this is (test) ...")); // → ["this is (test) ..."]
Explanation:
.* matches any character (except newline) between zero and unlimited times, as many times as possible.
[^)] match a single character but not the literal character )
This makes sure there's your test string in the given string, but it is only ever wrapped with one brace in every side!
You can use the following regex:
(^|[^(])(\(test\))(?!\))
See regex demo here, replace with $1<span style="new">$2</span>.
The regex features an alternation group (^|[^(]) that matches either start of string ^ or any character other than (. This alternation is a kind of a workaround since JS regex engine does not support look-behinds.
Then, (\(test\)) matches and captures (test). Note the round brackets are escaped. If they were not, they would be treated as a capturing group delimiters.
The (?!\)) is a look-ahead that makes sure there is no literal ) right after test). Look-aheads are supported fully by JS regex engine.
A JS snippet:
var re = /(^|[^(])(\(test\))(?!\))/gi;
var str = 'this is (test)\nthis is ((test))\nthis is ((test)\nthis is (test))\nthis is ((test\nthis is test))';
var subst = '$1<span style="new">$2</span>';
var result = str.replace(re, subst);
alert(result);
I have read How do you pass a variable to a Regular Expression javascript
I'm looking to create a regular expression to get and replace a value with a variable..
section = 'abc';
reg = new RegExp('\[' + section + '\]\[\d+\]','g');
num = duplicate.replace(reg,"$1++");
where $1 = \d+ +1
and... without increment... it doesn't work...
it returns something like:
[abc]$1
Any idea?
Your regex is on the right track, however to perform any kind of operation you must use a replacement callback:
section = "abc";
reg = new RegExp("(\\["+section+"\\]\\[)(\\d+)(\\])","g");
num = duplicate.replace(reg,function(_,before,number,after) {
return before + (parseInt(number,10)+1) + after;
});
I think you need to read up more on Regular Expressions. Your current regular expression comes out to:
/[abc][d+]/g
Which will match an "a" "b" or "c", followed by a "d" or "+", like: ad or c+ or bd or even zebra++ etc.
A great resource to get started is: http://www.regular-expressions.info/javascript.html
I see at least two problems.
The \ character has a special meaning in JavaScript strings. It is used to escape special characters in the string. For example: \n is a new line, and \r is a carriage return. You can also escape quotes and apostrophes to include them in your string: "This isn't a normally \"quoted\" string... It has actual \" characters inside the string as well as delimiting it."
The second problem is that, in order to use a backreference ($1, $2, etc.) you must provide a capturing group in your pattern (the regex needs to know what to backreference). Try changing your pattern to:
'\\[' + section + '\\]\\[(\\d+)\\]'
Note the double-backslashes. This escapes the backslash character itself, allowing it to be a literal \ in a string. Also note the use of ( and ) (the capturing group). This tells the regex what to capture for $1.
After the regex is instantiated, with section === 'abc':
new RegExp('\\[' + section + '\\]\\[(\\d+)\\]', 'g');
Your pattern is now:
/\[abc\]\[(\d+)\]/g
And your .replace will return \d+++ (where \d+ is the captured digits from the input string).
Demo: http://jsfiddle.net/U46yx/
im trying to replace all the dots and spaces in "
var name = "C. S. Lewis"
and replace them with _
and convert it into "C_S_LEWIS"
this is what i tried but it converts the whole thing into underscores (_)
var mystring = "C. S. Lewis";
var find = ".";
var regex = new RegExp(find, "g");
alert(mystring.replace(regex, "_"));
That's because dots need to be escaped in regular expressions (unless it's part of a character class). This expression should work:
var regex = /[.\s]+/g;
alert(mystring.replace(regex, '_'))
It matches a sequence of at least one period or space, which is then replaced by a single underscore in the subsequent .replace() call.
Btw, this won't save the new string back into mystring. For that you need to assign the results of the replacement operation back into the same variable:
mystring = mystring.replace(regex, '_')
The . means 'any character'. Use \. to get a literal dot, which means in your regex string you'd have to put \\. to get a literal underscore followed by a literal dot. But I'm not sure why you're making a string first - you could just do this:
var find = /\./g;
Of course, that's not what you're looking for - you want not just any dot, but just the dots followed by spaces. That's different:
var find = /\.\s+/g;
If I have a string, e.g.: "Consensus IRIS 2010-11 Series 6"
If someone types part of that string, e.g. "iris" into a textbox, how can I identify the substring in the original string?
I have the following, but it only matches when the string starts with the value from the text box.
var txt= $('#txtName').val();
var regExp = new RegExp("^" + txt, "i");
var t = item.name.replace(regExp, "<span class='matched-text'>" + txt + "</span>");
Side note: I am baffled by regular expressions!
Your problem comes from the fact that prepending "^" to your regular expression makes it only match at the beginning of the string/text box. Remove that and it should work as expected for normal substrings.
However, if someone types a regular expression into the search box, your code could have unexpected effects. For example, if someone typed in \w, every letter and number would be highlighted. This site is good for learning more about regular expressions.
Because your regular expression begins with ^ it will only match sequences that begin with whatever the value of txt is. Remove the ^ and you're set.
Try with this:
var regExp = new RegExp(txt, "i");
Or this:
var regExp = new RegExp("\b"+txt"\b", "i");
The first will match txt anywhere in the string, even in the middle of a word. The second will not match in the middle of a word.
I was trying to run this line of code and wondering why it is not working. Does anyone has an answer for this?
var string = "foo bar";
string = string.replace(" ", "");
alert(string.length);
why issit that the length of the string is not changed to 6 instead?
The function only replaces one instance of the string you search for.
To replace more, you can match with a regular expression:
string = string.replace(/\s+/g, '');
That strips all "whitespace" characters. The "\s" matches whitespace, the "+" means "one or more occurrences" of whitespace characters, and the trailing "g" means "do it to all matching sequences in the string".
Because you have more than one space in your string and the .replace is replacing one space, the first one encountered.
This works as expected, with only one space
var string = "foo bar";
string = string.replace(" ", "");
alert(string.length);
replace, when passed a string as the first parameter, only replaces the first occurrence of that string. To replace everything, you'd need a regular expression:
alert("foo bar".replace(/ /g, ""));
That's because only one space has been replaced. Per JavaScript 1.5 specification, String.replace() takes a regular expression as first parameter and the behavior for string parameters is undefined. Browsers later decided to treat strings similarly - but there is no way to specify g flag on a string, so only one replacement is done. This will do what you want:
string = string.replace(/ /g, '');
The version provided by Pointy (/\s+/g) might be more efficient however. And it will replace other types of whitespace (tabs, newlines) as well.