Use Regex to Replace the Starting substring - javascript

The following statement needs to be replaced, as in the following code
page_url.replace("www.", "");
This needs to be done with the use of regex. Please let me know the method of achieving the same.
Logically, it needs to replace the "www." with "" if and only if the string starts with www..

"www.test.com".replace(/^www\./, "") // returns "test.com"
or in long form:
var regex = /^www\./;
var stringToMatch = "www.test.com";
var result = stringToMatch.replace(regex, ""); // "test.com"
where the /^www\./ defines the regex object. This is made up of:
/ start of the regex
^ start of string, means this match must appear at the begining
www match the characters www
\. match the character .. We must escape it with \ because in regex . means match anything
/ end of the regex definition
If you wan't to play about with the regex to see how it works, try it in this web regex tester: https://regex101.com/r/7ErXz8/2

Related

Javascript: Remove trailing chars from string if they are non-numeric

I am passing codes to an API. These codes are alphanumeric, like this one: M84.534D
I just found out that the API does not use the trailing letters. In other words, the API is expecting M84.534, no letter D at the end.
The problem I am having is that the format is not the same for the codes.
I may have M84.534DAC, or M84.534.
What I need to accomplish before sending the code is to remove any non-numeric characters from the end of the code, so in the examples:
M84.534D -> I need to pass M84.534
M84.534DAC -> I also need to pass M84.534
Is there any function or regex that will do that?
Thank you in advance to all.
You can use the regex below. It will remove anything from the end of the string that is not a number
let code = 'M84.534DAC'
console.log(code.replace(/[^0-9]+?$/, ""));
[^0-9] matches anything that is not a numer
+? Will match between 1 and unlimited times
$ Will match the end of the string
So linked together, it will match any non numbers at the end of the string, and replace them with nothing.
You could use the following expression:
\D*$
As in:
var somestring = "M84.534D".replace(/\D*$/, '');
console.log(somestring);
Explanation:
\D stands for not \d, the star * means zero or more times (greedily) and the $ anchors the expression to the end of the string.
Given your limited data sample, this simple regular expression does the trick. You just replace the match with an empty string.
I've used document.write just so we can see the results. You use this whatever way you want.
var testData = [
'M84.534D',
'M84.534DAC'
]
regex = /\D+$/
testData.forEach((item) => {
var cleanValue = item.replace(regex, '')
document.write(cleanValue + '<br>')
})
RegEx breakdown:
\D = Anything that's not a digit
+ = One or more occurrences
$ = End of line/input

JavaScript - Regex: URL has a param

I'm trying to create an analog for php's isset ($_GET[param]) but for JavaScript.
So long, I get this
[?&]param[&=]
But if param is at the end of URL (example.com?param) this regex won't work.
You can play with it here: https://regex101.com/r/fFeWPW/1
If you want to make sure your match ends with &, = or end of string, you may replace the [&=] character class with a (?:[&=]|$) alternation group that will match &, = or end of string (note that $ cannot be placed inside the character class as it would lose its special meaning there and will be treated as a $ symbol), or you may use a negative lookahead (?![^&=]) that fails the match if there is no & or = immediately after the current location, which might be a bit more efficient than an alternation group.
So, in your case, it will look like
[?&]param(?:[&=]|$)
or
[?&]param(?![^&=])
See a regex demo
JS demo:
var strs = ['http://example.com?param', 'http://example.com?param=123', 'http://example.com?param&another','http://example.com?params'];
var rx = /[?&]param(?![^&=])/;
for (var s of strs) {
console.log(s, "=>", rx.test(s))
}

Regular expression for validating with specific characters through javascript

I want to validate a string that does not allows the following characters.
<,>,:,","/,\,|,?,*,#
I want to validate this through JavaScript.
I was trying this with the following code.
var reg = /[^a-zA-Z0-9 \-_]+/;
reg.test(filename[0])
But this was unable to validating the symbol #.
Please help.
The problem you have is that you included the hyphen in the middle of the pattern without escaping it. This tells the engine that you are expecting a range--in this case space through underscore. It's easier (in my opinion) to place the hyphen as either the first or last character in the pattern, at which point you don't have to escape it. (It would be the second character if you are using a negated character class.)
e.g.
var reg = /[^a-zA-Z0-9 \-_]+/;
--OR--
var reg = /[^a-zA-Z0-9 _-]+/;
--OR--
var reg = /[^-a-zA-Z0-9 _]+/;
Do you only want to allow English letters a-z (and A-Z), numbers, the space, '_', and '-'? If so, that is different than disallowing the characters you specified since '☃' doesn't have the characters you provided but may not be a valid string in your use case.
In the case you just want the English alphabet, numbers, space, '_', and '-', you can use the following RegExp and conditional:
var reg = /^[a-zA-Z0-9 \-_]+$/;
if (reg.test(filename[0])) {
// String is ok
}
This says everything in the string between beginning (^) and end ($) must be one or more of the allowed characters.
If you want to disallow the characters you provided in your question, you can use:
var reg = /[\<\>\:\,\/\\\|\?\*\#]/;
if (!reg.test(filename[0])) {
// String is ok
}
This says to search for any of the characters you've listed (they are all escaped with a \ before them) and if you find any, the string is invalid. So only if the test fails is the string a valid string - that's why there's a ! before the test.
string sourceString ="something" ;
var outString = sourceString.replace(/[`~!##$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');

Regex match Array words with dash

I want to match some keywords in the url
var parentURL = document.referrer;
var greenPictures = /redwoods-are-big.jpg|greendwoods-are-small.jpg/;
var existsGreen = greenPictures.test(parentURL);
var existsGreen turns true when it finds greendwoods-are-small.jpg but also when it finds small.jpg
What can i do that it only turns true if there is exactly greendwoods-are-small.jpg?
You can use ^ to match the beginning of a string and $ to match the end:
var greenPictures = /^(redwoods-are-big.jpg|greendwoods-are-small.jpg)$/;
var existsGreen = greenPictures.test(parentURL);
But of cause the document.referrer is not equal ether redwoods-are-big.jpg or greendwoods-are-small.jpg so i would match /something.png[END]:
var greenPictures = /\/(redwoods-are-big\.jpg|greendwoods-are-small\.jpg)$/; // <-- See how I escaped the / and the . there? (\/ and \.)
var existsGreen = greenPictures.test(parentURL);
Try this regex:
/(redwoods-are-big|greendwoods-are-small)\.jpg/i
I used the i flag for ignoring the character cases in parentURL variable.
Description
Demo
http://regex101.com/r/aI4yJ6
Dashes does not have any special meaning outside character sets, e.g.:
[a-f], [^x-z] etc.
The characters with special meaning in your regexp is | and .
/redwoods-are-big.jpg|greendwoods-are-small.jpg/
| denotes either or.
. matches any character except the newline characters \n \r \u2028 or \u2029.
In other words: There is something else iffy going on in your code.
More on RegExp.
Pages like these can be rather helpful if you struggle with writing regexp's:
regex101 (with sample)
RegexPlanet
RegExr
Debuggex
etc.

Regular expression giving incorrect output

I am using regex to verify that a string only contains alphabets and spaces. Regex is defined as
var regex = /^[A-Za-z ]/;
but even if I am testing it with a string "X," , it is giving a true result.
What is the error here?
^[A-Za-z ] only matches one character. and ^ means the start of the string. To accomplish what you want, use:
+ - This means match one or more. Alternatively you can use:
* - Which means match zero or more.
But I think you're better off with the first one (+). Another thing is, match for the whole string. This means you have to search from the first to the last character.
$ - This means match the end.
Your code should be like this:
var regex = /^[A-Za-z ]+$/;
Your regex matches the first letter of your input and therefore true is returned.. You need to add $ to make sure you only match a complete string from the beginning (^) to the end ($).
var regex = /^[A-Za-z ]*$/;
Try using this:
/^[a-zA-Z\ ]+$/
This is the correct way:
/^[A-Za-z ]*$/
Regex Demo

Categories

Resources