How to use a regular expression in this case [duplicate] - javascript

This question already has answers here:
How do you use a variable in a regular expression?
(27 answers)
Closed 2 months ago.
I want to check if a string-variable (called string) matches the following string: L-62000-64-000_0
My code looks like this:
let string = "L-62000-64-000_05641";
let part = 64;
const filter = new RegExp("^L-\d{5}-${part}-.+");
if (string.match(filter)) {
console.log("yes");
}
It is important, that the string starts with "L-". After this there should be a number with five digits and again a hyphen. The following two digits depend on a variable. After the variable there is again a hyphen. The rest of the string is not important for me. That's why I use the ".+"
The problem is, that this doesn't work and i don't know why...

if you want to use the part variable in the string, you need to use `` instead of ""
const filter = new RegExp(`^L-\d{5}-${part}-.+`);

You also need to add double \\ in this case
let string = 'L-62000-64-000_05641';
let part = 64;
const filter = new RegExp(`^L-\\d{5}-${part}-.+$`);
if (string.match(filter)) {
console.log("yes");
} else {
console.log("no");
}

Related

Cannot replace single emoji from a string [duplicate]

This question already has answers here:
Insert Unicode character into JavaScript
(6 answers)
Closed 2 years ago.
I have a string called completionBar which contains this:
let completionBar = `〚⬛⬛⬛⬛⬛〛`;
I'm trying to replace a single ⬛ with ⬜, so I tried:
completionBar.replace(/\U+2B1B/, 'U+2B1C');
but nothing happen, what I did wrong?
You can use /⬛/g in .replace().
I would try as the following if you want to replace all:
let completionBar = `〚⬛⬛⬛⬛⬛〛`;
const result = completionBar.replace(/⬛/g, '⬜');
console.log(result)
If you need only the first to replace:
let completionBar = `〚⬛⬛⬛⬛⬛〛`;
const result = completionBar.replace('⬛', '⬜');
console.log(result)
I hope this helps!
In my opinion, you can use escape and unescape function to show exactly the string code. It easy to debug and maintain the code.
let completionBar = `〚⬛⬛⬛⬛⬛〛`;
let escapeCompletionBar = escape(completionBar).replace(/u2B1B/g, 'u2B1C');
let result = unescape(escapeCompletionBar);

How to remove thousand separaters in number using javascript? [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 2 years ago.
problem:
I want to remove the comma in a string and make it as a number.
It means,
234,345 should become 234345.
1,234 should become 1234
4,567,890 should become 4567890
I have created one code like this.
let a = "5,245"
function numberWithoutCommas(x) {
return x.replace(",","");
}
const b = parseInt(numberWithoutCommas(a))
console.log(typeof(b))
console.log(b)
This is failing when there more comma in the string.It means 1,234,567 gives 1234. So can someone help me to achieve it?
Splitting and joining should do the job
return x.split(',').join('');
You can simply parse to a number and use a regex
const s = ['5,332', '39,322,322,233']
function numberWithoutCommas(x) {
return Number(x.replace(/,/g, ''));
}
for (const a of s) {
const n = numberWithoutCommas(a);
console.log(n, typeof n);
}
passing string as a first argument to replace method will only replace the very first occurrence.
let str = '111,11,11,1';
str.replace(',','') // result:- 11111,11,1
use regex instead
str.replace(/,/g,'') //result:- 11111111
in your use case
function numberWithoutCommas(x) {
return x.replace(/,/g,"");
}
The replace() method searches a string for a specified value, or a
regular expression, and returns a new string where the specified
values are replaced.
Note: If you are replacing a value (and not a regular expression),
only the first instance of the value will be replaced. To replace all
occurrences of a specified value, use the global (g) modifier.
So, to replace all the occurrences of ,, we should rather use /,/g instead of just ,.
Then your code would be something like the following
let a = "1,234,567"
function numberWithoutCommas(x) {
return x.replace(/,/g,"");
}
const b = parseInt(numberWithoutCommas(a))
console.log(typeof(b))
console.log(b)
I hope this helps :)

JS URL regex, allow only urls and empty string [duplicate]

This question already has answers here:
Regular expression which matches a pattern, or is an empty string
(5 answers)
Closed 2 years ago.
I have the following regext:
var regex = /^(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g;
function test() {
alert(regex.test(document.getElementById("myinput").value));
}
I want to allow url or empty string. regex solution please
How do I allow empty in this case?
https://jsfiddle.net/6kptovwc/2/
Thanks
Add an alternation with empty string (I've simplified a bit your regex):
^((?:https?:\/\/)?(?:www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b[-a-zA-Z0-9#:%_\+.~#?&\/=]*|)$
or
^((?:https?:\/\/)?(?:www\.)?[-\w#:%.+~#=]{2,256}\.[a-z]{2,6}\b[-\w#:%+.~#?&\/=]*|)$
Demo & explanation
Just add OR(||) condition
function test() {
const elm = document.getElementById("myinput")
alert(elm.value === '' || regex.test(elm.value));
}
^$|pattern
var regex = /^$|(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g;

javascript: is there any elegant way to check if string contains any of characters given in an array [duplicate]

This question already has answers here:
Call a function if a string contains any items in an array
(3 answers)
Closed 8 years ago.
I have a string in my JavaScript code (plain JavaScript, no jQuery or any other libs involved). And also I have an array which contains characters to be found in a string. I need to check if string contains any of those characters. Of course, it could be done with temporary variable like found and array elements iteration.
But is there any way to write nice and compact code? Just in case, I use ES5 (IE9+).
I want to achieve something like
var str = "Here is the string",
chars = ['z','g'];
if (str.containsAnyOf(chars)) {
...
}
What is the best way to write that piece of code?
You can use Array.prototype.some, like this
if (chars.some(function(c) { return str.indexOf(c) !== -1; })) {
// Atleast one of the characters is present
};
Consider using regular expression:
var str = "Here is the string",
chars = ['z','g'];
// constructs the following regexp: /[zg]/
if (new RegExp("[" + chars.join('') + "]").test(str)) {
alert("Contains!");
}

How to extract numbers from string in Javascript using regex [duplicate]

This question already has answers here:
Find and get only number in string
(4 answers)
Closed 8 years ago.
I have the following string
/Date(1317772800000)/
I want to use a Javascript regular expression to extract the numerical portion of it
1317772800000
How is this possible?
That should be it
var numPart = "/Date(1317772800000)/".match(/(\d+)/)[1];
No need for regex. Use .substring() function. In this case try:
var whatever = "/Date(1317772800000)/";
whatever = whatever.substring(6,whatever.length-2);
This'll do it for you: http://regex101.com/r/zR0wH4
var re = /\/Date\((\d{13})\)\//;
re.exec('/Date(1317772800000)/');
=> ["/Date(1317772800000)/", "1317772800000"]
If you don't care about matching the date portion of the string and just want extract the digits from any string, you can use this instead:
var re = /(\d+)/;
re.exec('/Date(1317772800000)/')
["1317772800000", "1317772800000"]

Categories

Resources