Regex that only works on browser tester - javascript

I've tested my regex on Regex testers and it worked, but I didn't get it to work on my code.
var mail = "chdelfosse#gmail.com";
var regExp = new RegExp("#(.*?)\.");
document.write(regExp.exec(mail)) ;
I get this result :
#g,
I tried to add a backslash before the dot, and I got this :
#gmail.,gmail
I also wanted to remove the "#" and the "." from the email, so I tried to use " (?:#) ", but I didn't get it to work (on Regex testers).
It's my first time trying to use Regex, and I don't get it.
Why is there a comma ?

You can use this regex to get the domain name:
/#(.+)\./
Live DEMO

Faster than regex:
var emailAddress = "my.email#gmail.com";
var array_email = emailAddress.split("#");​​
alert('Account: ' + array_email[0] +'; Domain: ' + array_email[1]);​​​​​​​​​​​​​​​​​​​​​​​​​​

A couple things to do differently:
You need to double escape your backslash in the string so that one backslash still remains for the RegExp constructor or switch to the /regex here/ syntax.
If you want just the subgroup in the parens, you need to refer to that specific subgroup.
Here's the code:
var mail = "chdelfosse#gmail.com";
console.log(mail.match(/#(.*?)\./)[1]);

Related

How do I split a string between / and "+" based on an outgoing link click, when there are colons in the actual URL?

JS Beginner here. I need to return itemName from a URL string, however, there are colons in the URL itself. When I split using ("""), I get an error that this won't work.
I have gotten this far, but I don't know what to change in my function to get the desired result. See the examples below:
Below is the URL:
"https://www.website.com/items/item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2"
Below you can see my code.
if ({{Outgoing link}})
var itemName= {{Click URL}};
return itemName.split("/")[5].split(".")[0];
console.log(extractSliceFromUrl(itemName))
}
This is my expected result:
"item-name-1"
This is the actual result I get:
"item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2"
Would the following work?
It extracts whatever's between the last / and the first "+".
const url = "\"https://www.website.com/items/item-name-1\"+\"?date_1=2022-10-05&date_2=2022-10-07&amount=2\"";
console.log(url.substring(url.lastIndexOf('/') + 1, url.indexOf('"+"')));
I'd split by ? first:
const theURL = "https://www.website.com/items/item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2";
theURL.split("?")[0].split("/")[5].split(".")[0];
With the secondary result, you could just remove the ending using:
'"item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2"'.replace(/("[^"]+?")\+/, '$1')
Explanation of /("[^"]+?")\+/ (RegExp)
(...) catch the pattern (becomes the $1)
[^"] everything not "
+? get the shortest result possible
\+ escape + (+ is a special symbol, this will treat it as plain text)
please is the working code.
let strUrl = "https://www.website.com/items/item-name-1"+"?date_1=2022-10-05&date_2=2022-10-07&amount=2";
let urlArray = strUrl.split("/");
let itemName = urlArray[4].split("?")[0];
console.log(itemName);

decimal emoji with using regex

I want to change my keyboard character with sad emoji using html decimal code and javascript regex. I just want to conflate that two characters ':' and '('
How can I write that emojiSmile regex variable?
Here are my code below.
var finalAnswer = ':)';
var emojiSmile = /\:+[)]/g;
var emojiSmileDecimal = '😊';
if (finalAnswer.match(emojiSmile)) {
var emojies = finalAnswer.replace(emojiSmile, emojiSmileDecimal);
}
It already works as you wrote it.
From first principles, you just need to escape the ) as \) because it's a special character in regex syntax:
var emojiSmile = /:\)/g;
Escaping it with brackets ([)]), like you did, also works:
var emojiSmile = /:[)]/g;
There is no need to escape : or to put a + behind it (unless you want to match ::::) as well).

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)

Match #(\w+) and replace in javascript

I'm trying to match #(\w+) in a div content and remove it.
Here's what i've tried : http://jsfiddle.net/mxgde6m7/1/ .
#(\w+) works , but it doesn't replace with space.
var content = document.getElementById('contentbox');
var find = '#(\w+)';
var reg = new RegExp(find, 'g');
var result = content.innerHTML.replace(reg, ' ');
alert(result);
<div id="contentbox">#d test
What i want: <div id="contentbox">test
</div>
Thanks in advance.
EDIT
Okay, one problem solved, another one came up.
My script http://jsfiddle.net/mxgde6m7/9/ works perfectly there, but when i try it on my website, only a half works. The last part where it should replace #(\w+) with space doesn't work at all. If i copy/paste the CONTENT of the function in console(chrome), it works , but if i paste the function and i call it, it doesn't work.
Please help ! I'm stuck.
Using a RegExp constructor, you need two backslashes \\ in place of each backslash \.
var find = '#(\\w+)';
hwnd is correct that you need to double escape \w in your regular expression.
var find = '#(\\w+)';
But, you could also make this code much cleaner by defining a regex literal like so -
var content = document.getElementById('contentbox');
var result = content.innerHTML.replace(/#(\w+)/g, ' ');
alert(result);
Doing it this way doesn't require double escaping, as it's not a string.

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