How to test pattern regexpr in javascript [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
In javascript I have a string containing a pattern '/^\d{7,15}$/' and I would test string str1
How can I use this string '/^\d{7,15}$/' ???
var re = '/^\d{7,15}$/';
var str1 = '12345678'; //should match!
// none of the below methods is working to me
var m1 = str1.match(re);
console.log(m1); //null
var regex1 = new RegExp(re);
var t1 = regex1.test(str1);
console.log(t1); //false

You need to escape your backslash \ in your string literal:
var re = '^\\d{7,15}$';
var str1 = '12345678'; //should match!
var regex1 = new RegExp(re);
var t1 = regex1.test(str1);
console.log(t1);
I also removed the slashes / around your expression, as they are not required. As Paulpro mentions in the comments, if you do not control the input string, you can strip them out with str1.slice(1, -1).

Related

Javascript replace using key mappings and regex [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am attempting to create a function that encodes special characters in a url. I looked into the npm package: urlencode but it doesn't encode all characters for some reason (such as parenthesis). I start by replacing the percent symbol so there is no interference with the rest of the code replacements. I made a mapObj array to feed into a regex and for some reason all of these characters are not getting replaced. The parenthesis and the periods especially. Any idea why?
const replaceSpecialChars = function (str) {
str = str.replace('%', '%25')
var mapObj = {
"&":"%26",
"`":"%60",
"-":"%2D",
"|":"%7C",
".":"%2E",
"(":"%28",
")":"%29"
};
var re = new RegExp(Object.keys(mapObj).map(key => key.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')).join('|'));
str = str.replace(re, function(matched){
return mapObj[matched];
});
}
I believe you have overcomplicated it a little bit, single String#replace is enough.
var mapObj = {
"&": "%26",
"`": "%60",
"-": "%2D",
"|": "%7C",
".": "%2E",
"(": "%28",
")": "%29"
};
const replaceSpecialChars = (str) =>
str.replace(/./g, (m) => mapObj[m] ?? m);
console.log(replaceSpecialChars('&_-_(_)_.'));

How to escape the double forwardslash in regex (javascript) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
How to replace the specific string only using one replace instead of two?
const formattedUrl = url.replace('flashget://', '').replace('&abc','')
What I have tried: (Not Working)
const formattedUrl = url.replace(/flashget:\/\/ | &abc/g, '').replace('&abc','')
Example
Input Url: flashget://W0ZMQVNIR0VUXWh0dHA6Ly93d3cuZm9yZWNlLm5ldC93aW43LnJhcltGTEFTSEdFVF0=&abc
Formatted Url: W0ZMQVNIR0VUXWh0dHA6Ly93d3cuZm9yZWNlLm5ldC93aW43LnJhcltGTEFTSEdFVF0=
Take out the spaces around the |
This is my attempt:
https://regex101.com/r/eFO7Eh/2
Search Regex:
flashget:\/\/(.*)\&.*$
Replace term:
$1
Just pay attention to the fact that this is a different logic and requires handling capture groups.
remove the space before and after the or |. it will work.
let url = "flashget://W0ZMQVNIR0VUXWh0dHA6Ly93d3cuZm9yZWNlLm5ldC93aW43LnJhcltGTEFTSEdFVF0=&abc"
const formattedUrl = url.replace(/flashget:\/\/|&abc/g, '');
console.log(formattedUrl);

Issue With Replacing RegExp Terms In String [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
var testString = "This string has a bad word in it to test";
function findBadWords(string) {
var badWord = /\bbad\b | \bword\b | \btest\b/gi
var isBadWord = string.match(badWord);
if (isBadWord) {
newString = string.replace(badWord," *** ");
}
document.write(newString);
}
findBadWords(testString);
So I'm practicing with RegExp's currently and I have run into a problem I don't understand. In the code above, I have set a RegExp to find "bad words" in a string. From what I can tell, I have set it to find the word "bad", "word", and "test" as long as there is a word boundary before and after the word. The issue I'm having is that "word" isn't being replaced. If I put a non-badWord before "word" it gets replaced, but not otherwise. I have tried taking off some of the word boundaries or adding some non-word boundaries with no luck. Would anyone mind explaining why this code is working the way that it is and how I could fix it?
Thanks!
Also, I know using document.write is a poor choice but it's only for testing I swear!
The issue here is the \b alongside the " " empty space character. If you remove the spaces from your regex it works well.
var testString = "This string has a bad word in it to test";
function findBadWords(string) {
var badWord = /\bbad\b|\bword\b|\btest\b/gi
var isBadWord = string.match(badWord);
if (isBadWord) {
newString = string.replace(badWord," *** ");
}
document.write(newString);
}
findBadWords(testString);

Javascript regular exp not working correctly [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I wrote this JS code for validating the password must not contain the (!) char.
fiddle : http://jsfiddle.net/sr8xm/
var pattern = /[A-Za-z0-9.#&#_-]{6,20}/;
$("#pwd").blur(function(){
pwd = $(this).val();
if(!pattern.test(pwd)){
alert('Please enter valid new password.');
return false;
}
});
but this returns true if someone type ! char after 6 chars ??
any idea what going wrong in this.
Anchor your regex:
var pattern = /^[A-Za-z0-9.#&#_-]{6,20}$ /;
You could also reduce it to:
var pattern = /^[\w.#&#-]{6,20}$/;
/[A-Za-z0-9.#&#_-]{6,20}/ can match the middle part of the password string. For example it matches "!mypassword!" and return true. You'd use ^ (matches the beginning of the string) and $ (matches the end of the string) like /^[A-Za-z0-9.#&#_-]{6,20}$/.
If you want to restrict your chosen characters, you can use another expression which will check presence of restricted characters. But anchoring regex is also quick solution for your prob
var pattern = /[A-Za-z0-9.#&#_-]{6,20}/g;
var restrictedChar =/[!]+/g; // Add more character here which u want to restrict
var pwd = $("#pwd").val();
if(!pattern.test(pwd) || restrictedChar.test(pwd)){
alert('Please enter valid new password.');
return false;
}
Demo

Remove two same string from a string [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
var string = "user1,user2,user1,user3,user4,user1,";
I want to remove all 'user1,' from the string but by 'replace' method I can just remove one of them.
use regexp
var string = "user1,user2,user1,user3,user4,user1,";
string.replace(/user1/g, '');
EDITED CODE
var string = "user1,user2,user1,user3,user4,user1,";
var find = 'user1';
var re = new RegExp(find, 'g');
string = string.replace(re, '');
http://jsfiddle.net/79DgJ/
var str= "user1,user2,user1,user3,user4,user1,";
str = str.replace(/user1,/g, ''); //replaces all 'user1,'
First parameter replace method can be regular expression.
Use option 'g' for replace all matches.
var string = "user1,user2,user1,user3,user4,user1,";
string = string.replace(/user1,/g, '');
try this,
split the string, get the array, filter it to remove duplicate items, join them back.
var uniqueList=string.split(',').filter(function(item,i,allItems){
return i==allItems.indexOf(item);
}).join(',');
Fiddle
try out this..
var string = "user1,user2,user1,user3,user4,user1,";
string.replace(/user1,/g, '');
alert('string .. '+string);

Categories