How to to extract a string between two characters? - javascript

These are my strings:
there_is_a_string_here_1_480#1111111
there_is_a_string_here_1_360#1111111
there_is_a_string_here_1_180#1111111
What I want to do is extracting 180, 360 and 480 from those strings.
I tried this RegEx _(.*)# but no chance.

You just want the capture group:
var str = 'there_is_a_string_here_1_180#1111111';
var substr = str.match(/_(\d*)#/);
if (substr) {
substr = substr[1];
console.log(substr);
}
//outputs 180

you almost got it
_(\d{3})#
you need to do a match on digits, or else the string will also get selected because of the other underscore.
Ofcourse your match will be in \1

Try this
var str = "there_is_a_string_here_1_480#1111111";
var matches = str.match(/_\d+#/).map(function(value){return value.substring(1,value.length-1);});
document.body.innerHTML += JSON.stringify(matches,0,4);

try this:
(?<=(?!.*))(.*)(?=#)
Use lookbehind (?<=) and look ahead (?=) so that "_" and "#" are not included in the match.
(?!.*) gets the last occurence of "_".
(.*) matches everything between the last occurence of "_" and "#".
I hope it helps.

Related

How to regex replace a query string with matching 2 words?

I have a url and I want to replace the query string. For example
www.test.com/is/images/383773?wid=200&hei=200
I want to match the wid= and hei= and the numbers don't have to be 200 to replace the whole thing so it should look like this.
Expected
www.test.com/is/images/383773?#HT_dtImage
So I've tried doing but it only replaced the matching wei and hei.
const url = "www.test.com/is/images/383773?wid=200&hei=200"
url.replace(/(wid)(hei)_[^\&]+/, "#HT_dtImage")
You can match either wid= or hei= until the next optional ampersand and then remove those matches, and then append #HT_dtImage to the result.
\b(?:wid|hei)=[^&]*&?
The pattern matches:
\b A word boundary to prevent a partial word match
(?:wid|hei)= Non capture group, match either wid or hei followed by =
[^&]*&? Match 0+ times a char other than &, and then match an optional &
See a regex demo.
let url = "www.test.com/is/images/383773?wid=200&hei=200"
url = url.replace(/\b(?:wid|hei)=[^&]*&?/g, "") + "#HT_dtImage";
console.log(url)
I would just use string split here:
var url = "www.test.com/is/images/383773?wid=200&hei=200";
var output = url.split("?")[0] + "?#HT_dtImage";
console.log(output);
If you only want to target query strings havings both keys wid and hei, then use a regex approach:
var url = "www.test.com/is/images/383773?wid=200&hei=200";
var output = url.replace(/(.*)\?(?=.*\bwid=\d+)(?=.*\bhei=\d+).*/, "$1?#HT_dtImage");
console.log(output);
You can make use of lookaround using regex /\?.*/
const url = 'www.test.com/is/images/383773?wid=200&hei=200';
const result = url.replace(/\?.*/, '?#HT_dtImage');
console.log(result);
Try
url.replace(/\?.*/, "?#HT_dtImage")

JS Regex for a string contains fixed number of letters

Let's say I need to have minimum 5 letters in a string not requiring that they are subsequent. The regex below checks subsequent letters
[A-Za-z]{5,}
So, "aaaaa" -- true, but "aaa1aa" -- false.
What is the regex to leave the sequence condition, that both of the strings above would pass as true.
You could remove all non-letter chars with .replace(/[^A-Za-z]+/g, '') and then run the regex:
var strs = ["aaaaa", "aaa1aa"];
var val_rx = /[a-zA-Z]{5,}/;
for (var s of strs) {
console.log( val_rx.test(s.replace(/[^A-Za-z]+/g, '')) );
}
Else, you may also use a one step solution like
var strs = ["aaaaa", "aaa1aa"];
var val_rx = /(?:[^a-zA-Z]*[a-zA-Z]){5,}/;
for (var s of strs) {
console.log( s, "=>", val_rx.test(s) );
}
See this second regex demo online. (?:[^a-zA-Z]*[a-zA-Z]){5,} matches 5 or more consecutive occurrences of 0 or more non-letter chars ([^a-zA-Z]*) followed with a letter char.
Allow non-letter characters between the letters:
(?:[A-Za-z][^A-Za-z]*){5,}
If you have to use a regular expression only, here's one somewhat ugly option:
const check = str => /^(.*[A-Za-z].*){5}/.test(str);
console.log(check("aaaaa"));
console.log(check("aa1aaa"));
console.log(check("aa1aa"));
w means alphanumeric in regex,
it will be ok : \w{5,}
[a-zA-Z0-9]{5,}
Just like this? Or do you mean it needs to be a regex that ignores digits? Because the above would match aaaa1 as well.

Replace after char '-' or '/' match

I'm trying to execute regex replace after match char, example 3674802/3 or 637884-ORG
The id can become one of them, in that case, how can I use regex replace to match to remove after the match?
Input var id = 3674802/3 or 637884-ORG;
Expected Output 3674802 or 637884
You could use sbustring method to take part of string only till '/' OR '-':
var input = "3674802/3";
var output = input.substr(0, input.indexOf('/'));
var input = "637884-ORG";
var output = input.substr(0, input.indexOf('-'));
var input = "3674802/3";
if (input.indexOf('/') > -1)
{
input = input.substr(0, input.indexOf('/'));
}
console.log(input);
var input = "637884-ORG";
if (input.indexOf('-') > -1)
{
input = input.substr(0, input.indexOf('-'));
}
console.log(input);
You can use a regex with a lookahead assertion
/(\d+)(?=[/-])/g
var id = "3674802/3"
console.log((id.match(/(\d+)(?=[/-])/g) || []).pop())
id = "637884-ORG"
console.log((id.match(/(\d+)(?=[/-])/g) || []).pop())
You don't need Regex for this. Regex is far more powerful than what you need.
You get away with the String's substring and indexOf methods.
indexOf takes in a character/substring and returns an integer. The integer represents what character position the character/substring starts at.
substring takes in a starting position and ending position, and returns the new string from the start to the end.
If are having trouble getting these to work; then, feel free to ask for more clarification.
You can use the following script:
var str = '3674802/3 or 637884-ORG';
var id = str.replace(/(\d+)[-\/](?:\d+|[A-Z]+)/g, '$1');
Details concerning the regex:
(\d+) - A seuence of digits, the 1st capturing group.
[-\/] - Either a minus or a slash. Because / are regex delimiters,
it must be escaped with a backslash.
(?: - Start of a non-capturing group, a "container" for alternatives.
\d+ - First alternative - a sequence of digits.
| - Alternative separator.
[A-Z]+ - Second alternative - a sequence of letters.
) - End of the non-capturing group.
g - global option.
The expression to replace with: $1 - replace the whole finding with
the first capturing group.
Thanks To everyone who responded to my question, was really helpful to resolve my issue.
Here is My answer that I built:
var str = ['8484683*ORG','7488575/2','647658-ORG'];
for(i=0;i<str.length;i++){
var regRep = /((\/\/[^\/]+)?\/.*)|(\-.*)|(\*.*)/;
var txt = str[i].replace(regRep,"");
console.log(txt);
}

How to remove the first and the last character of a string

I'm wondering how to remove the first and last character of a string in Javascript.
My url is showing /installers/ and I just want installers.
Sometimes it will be /installers/services/ and I just need installers/services.
So I can't just simply strip the slashes /.
Here you go
var yourString = "/installers/";
var result = yourString.substring(1, yourString.length-1);
console.log(result);
Or you can use .slice as suggested by Ankit Gupta
var yourString = "/installers/services/";
var result = yourString.slice(1,-1);
console.log(result);
Documentation for the slice and substring.
It may be nicer one to use slice like :
string.slice(1, -1)
I don't think jQuery has anything to do with this. Anyway, try the following :
url = url.replace(/^\/|\/$/g, '');
If you dont always have a starting or trailing slash, you could regex it. While regexes are slower then simple replaces/slices, it has a bit more room for logic:
"/installers/services/".replace(/^\/?|\/?$/g, "")
# /installers/services/ -> installers/services
# /installers/services -> installers/services
# installers/services/ -> installers/services
The regex explained:
['start with' ^] + [Optional?] + [slash]: ^/?, escaped -> ^\/?
The pipe ( | ) can be read as or
['ends with' $] + [Optional ?] + [slash] -> /?$, escaped -> \/?$
Combined it would be ^/?|/$ without escaping. Optional first slash OR optional last slash.
Technically it isn't "optional", but "zero or one times".
You can do something like that :
"/installers/services/".replace(/^\/+/g,'').replace(/\/+$/g,'')
This regex is a common way to have the same behaviour of the trim function used in many languages.
A possible implementation of trim function is :
function trim(string, char){
if(!char) char = ' '; //space by default
char = char.replace(/([()[{*+.$^\\|?])/g, '\\$1'); //escape char parameter if needed for regex syntax.
var regex_1 = new RegExp("^" + char + "+", "g");
var regex_2 = new RegExp(char + "+$", "g");
return string.replace(regex_1, '').replace(regex_2, '');
}
Which will delete all / at the beginning and the end of the string. It handles cases like ///installers/services///
You can also simply do :
"/installers/".substring(1, string.length-1);
You can use substring method
s = s.substring(0, s.length - 1) //removes last character
another alternative is slice method
if you need to remove the first leter of string
string.slice(1, 0)
and for remove last letter
string.slice(0, -1)
use .replace(/.*\/(\S+)\//img,"$1")
"/installers/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services
"/services/".replace(/.*\/(\S+)\//img,"$1"); //--> services
It is too nicer shortcode.
response.data.slice(1,-1) // "Prince"
-> Prince
url=url.substring(1,url.Length-1);
This way you can use the directories if it is like .../.../.../... etc.

Regular Expression: Any character that is not a letter or number

I need a regular expression that will match any character that is not a letter or a number. Once found I want to replace it with a blank space.
To match anything other than letter or number you could try this:
[^a-zA-Z0-9]
And to replace:
var str = 'dfj,dsf7lfsd .sdklfj';
str = str.replace(/[^A-Za-z0-9]/g, ' ');
This regular expression matches anything that isn't a letter, digit, or an underscore (_) character.
\W
For example in JavaScript:
"(,,#,£,() asdf 345345".replace(/\W/g, ' '); // Output: " asdf 345345"
You are looking for:
var yourVar = '1324567890abc§$)%';
yourVar = yourVar.replace(/[^a-zA-Z0-9]/g, ' ');
This replaces all non-alphanumeric characters with a space.
The "g" on the end replaces all occurrences.
Instead of specifying a-z (lowercase) and A-Z (uppercase) you can also use the in-case-sensitive option: /[^a-z0-9]/gi.
This is way way too late, but since there is no accepted answer I'd like to provide what I think is the simplest one: \D - matches all non digit characters.
var x = "123 235-25%";
x.replace(/\D/g, '');
Results in x: "12323525"
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
Match letters only /[A-Z]/ig
Match anything not letters /[^A-Z]/ig
Match number only /[0-9]/g or /\d+/g
Match anything not number /[^0-9]/g or /\D+/g
Match anything not number or letter /[^A-Z0-9]/ig
There are other possible patterns
try doing str.replace(/[^\w]/);
It will replace all the non-alphabets and numbers from your string!
Edit 1: str.replace(/[^\w]/g, ' ')
Just for others to see:
someString.replaceAll("([^\\p{L}\\p{N}])", " ");
will remove any non-letter and non-number unicode characters.
Source
To match anything other than letter or number or letter with diacritics like é you could try this:
[^\wÀ-úÀ-ÿ]
And to replace:
var str = 'dfj,dsf7é#lfsd .sdklfàj1';
str = str.replace(/[^\wÀ-úÀ-ÿ]/g, '_');
Inspired by the top post with support for diacritics
source
Have you tried str = str.replace(/\W|_/g,''); it will return a string without any character and you can specify if any especial character after the pipe bar | to catch them as well.
var str = "1324567890abc§$)% John Doe #$#'.replace(/\W|_/g, ''); it will return str = 1324567890abcJohnDoe
or look for digits and letters and replace them for empty string (""):
var str = "1324567890abc§$)% John Doe #$#".replace(/\w|_/g, ''); it will return str = '§$)% #$#';
Working with unicode, best for me:
text.replace(/[^\p{L}\p{N}]+/gu, ' ');

Categories

Resources