Search for a string with a point in JavaScript - javascript

When I try to seach for a string with a point (i.e. '1.'), js also points to substrings with commas instead of points. It's better to look at the example:
'1,'.search('1.'); // 0
'xxx1,xxx'.search('1.'); // 3
// Normal behaviour
'1.'.search('1,'); // -1
Does anyone know why JavaScript behave itself so?
Is there a way to search for exactly passed string?

Per the docs:
The search() method executes a search for a match between a regular expression and this String object.
. has a special meaning in Regular Expressions. You need to escape the . before matching it. Try the following:
console.log('xxx1,xxx'.search('1\\.'));

Use indexOf().
let str = "abc1,231.4";
console.log(str.indexOf("1."));

indexOf() method should work fine in this case
'1,'.indexOf('1.');
The above code should return -1

String.search is taking regex as parameter.
Regex evaluate . by any character; you gotta escape it using double anti-slash \\.
console.log('1,'.search('1\\.'));
console.log('xxx1,xxx'.search('1\\.'));
console.log('xxx1.xxx'.search('1\\.'));
console.log('1.'.search('1,'));

Related

Why would the replace with regex not work even though the regex does?

There may be a very simple answer to this, probably because of my familiarity (or possibly lack thereof) of the replace method and how it works with regex.
Let's say I have the following string: abcdefHellowxyz
I just want to strip the first six characters and the last four, to return Hello, using regex... Yes, I know there may be other ways, but I'm trying to explore the boundaries of what these methods are capable of doing...
Anyway, I've tinkered on http://regex101.com and got the following Regex worked out:
/^(.{6}).+(.{4})$/
Which seems to pass the string well and shows that abcdef is captured as group 1, and wxyz captured as group 2. But when I try to run the following:
"abcdefHellowxyz".replace(/^(.{6}).+(.{4})$/,"")
to replace those captured groups with "" I receive an empty string as my final output... Am I doing something wrong with this syntax? And if so, how does one correct it, keeping my original stance on wanting to use Regex in this manner...
Thanks so much everyone in advance...
The code below works well as you wish
"abcdefHellowxyz".replace(/^.{6}(.+).{4}$/,"$1")
I think that only use ()to capture the text you want, and in the second parameter of replace(), you can use $1 $2 ... to represent the group1 group2.
Also you can pass a function to the second parameter of replace,and transform the captured text to whatever you want in this function.
For more detail, as #Akxe recommend , you can find document on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace.
You are replacing any substring that matches /^(.{6}).+(.{4})$/, with this line of code:
"abcdefHellowxyz".replace(/^(.{6}).+(.{4})$/,"")
The regex matches the whole string "abcdefHellowxyz"; thus, the whole string is replaced. Instead, if you are strictly stripping by the lengths of the extraneous substrings, you could simply use substring or substr.
Edit
The answer you're probably looking for is capturing the middle token, instead of the outer ones:
var str = "abcdefHellowxyz";
var matches = str.match(/^.{6}(.+).{4}$/);
str = matches[1]; // index 0 is entire match
console.log(str);

How can I use regex to match a string without double characters

I've got a block of text that I want to run some regex on in javascript, to match [code]. I know I can use /\[code\]/g to do this.
However, I want to ignore cases where double brackets are used, as in[[code]]. So in other words, in the string [code] [[code]] [code], only the first and last occurrences should match.
Is this possible?
http://regexr.com/395kr
JS does not support negative lookbehind assertions, but seems like the negative lookahead is enough in your case:
'[code] [[code]] [code]'.match(/\[code\](?!\])/g)
This regex ensures that the next character after matched [code] is not a ]
UPD:
It could be improved to
'[code] [[code]] [code]'.match(/\[(?!\[)code\](?!\])/g)
thanks to Felix Kling.
A note: it will behave weird in case of unpaired braces.
You can use filter() for this:
var data = "[code] [[code]] [code]";
data = data.match(/\[+code\]+/g) // gives us ["[code]", "[[code]]", "[code]"]
.filter(function(x) { return !x.match(/\[\[code\]\]/); });
// data is now ["[code]", "[code]"]
Felix's method also works nicely.

What seems to be a correct regex doesn't work in replace function

I am trying to match three consecutive dots (".") followed optionally by a space.
My idea was the following:
\.\.\.\s?
Tested it here and seems to do exactly as expected.
But then when I try to use it in the replace function with javascript it doesn't seem to work, it's quite weird unless I'm missing something silly:
replace("\.\.\.\s?", "")
Doesn't work, see live demo here.
What am I missing?
The regex shouldn't be in quotes. Try...
mystr.replace(/\.\.\.\s?/, "")
jsfiddle
this should work $('div').text("... hi".replace(/\.\.\.\s?/, ""));
String.replace() takes either a string or a regular expression as the first argument. If it is a string then it is searched for verbatim. https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/replace
The first parameter of String.replace must be a RegExp object, not String. Change it to:
$('div').text("... hi".replace(/\.\.\.\s?/, ""));
Or,
$('div').text("... hi".replace(new RegExp("\\.\\.\\.\\s?"), ""));
$('div').text("... hi".replace(/\.{3}/gi, ""));
Slightly optimized regular expression.

Non-capturing groups in Javascript regex

I am matching a string in Javascript against the following regex:
(?:new\s)(.*)(?:[:])
The string I use the function on is "new Tag:var;"
What it suppod to return is only "Tag" but instead it returns an array containing "new Tag:" and the desired result as well.
I found out that I might need to use a lookbehind instead but since it is not supported in Javascript I am a bit lost.
Thank you in advance!
Well, I don't really get why you make such a complicated regexp for what you want to extract:
(?:new\\s)(.*)(?:[:])
whereas it can be solved using the following:
s = "new Tag:";
var out = s.replace(/new\s([^:]*):.*;/, "$1")
where you got only one capturing group which is the one you're looking for.
\\s (double escaping) is only needed for creating RegExp instance.
Also your regex is using greedy pattern in .* which may be matching more than desired.
Make it non-greedy:
(?:new\s)(.*?)(?:[:])
OR better use negation:
(?:new\s)([^:]*)(?:[:])

JS - RegExp for detecting ".-" , "-."

I am bit confused with the RegExp I should be using to detect ".-", "-." it indeed passes this combinations as valid but in the same time, "-_","_-" get validated as well. Am I missing something or not escaping something properly?
var reg=new RegExp("(\.\-)|(\-\.)");
Actually seems any combination containing '-' gets passed. it
Got it thank you everyone.
You need to use
"(\\.-)|(-\\.)"
Since you're using a string with the RegExp constructor rather than /, you need to escape twice.
>>> "asd_-ads".search("(\.\-)|(\-\.)")
3
>>> "asd_-ads".search(/(\.\-)|(\-\.)/)
-1
>>> "asd_-ads".search(new RegExp('(\\.\-)|(\-\\.)'))
-1
In notation /(\.\-)|(\-\.)/, the expression would be right.
In the notation you chose, you must double all backslashes, because it still has a special meaning of itself, like \\, \n and so on.
Note there is no need to escape the dash here: var reg = new RegExp("(\\.-)|(-\\.)");
If you don't need to differentiate the matches, you can use a single enclosing capture, or none at all if you only want to check the match: "\\.-|-\\." is still valid.
You are using double quotes so the . doesn't get escaped with one backslash, use this notation:
var reg = /(\.\-)|(\-\.)/;

Categories

Resources