Looking to trim a string using javascript / regex [duplicate] - javascript

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
I'm looking for some assistance with JavaScript/Regex when trying to format a string of text.
I have the following IDs:
00A1234/A12
0A1234/A12
A1234/A12
000A1234/A12
I'm looking for a way that I can trim all of these down to 1234/A12. In essence, it should find the first letter from the left, and remove it and any preceding numbers so the final format should be 0000/A00 or 0000/AA00.
Is there an efficient way this can be acheived by Javascript? I'm looking at Regex at the moment.

Instead of focussing on what you want to strip, look at what you want to get:
/\d{4}\/[A-Z]{1,2}\d{2}/
var str = 'fdfhfjkqhfjAZEA0123/A45GHJqffhdlh';
match = str.match(/\d{4}\/[A-Z]{1,2}\d{2}/);
if (match) console.log(match[0]);

You could seach for leading digits and a following letter.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'],
regex = /^\d*[a-z]/gi;
data.forEach(s => console.log(s.replace(regex, '')));
Or you could use String#slice for the last 8 characters.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'];
data.forEach(s => console.log(s.slice(-8)));

You could use this function. Using regex find the first letter, then make a substring starting after that index.
function getCode(s){
var firstChar = s.match('[a-zA-Z]');
return s.substr(s.indexOf(firstChar)+1)
}
getCode("00A1234/A12");
getCode("0A1234/A12");
getCode("A1234/A12");
getCode("000A1234/A12");

A regex such as this will capture all of your examples, with a numbered capture group for the bit you're interested in
[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})
var input = ["00A1234/A12","0A1234/A12","A1234/A12","000A1234/A12"];
var re = new RegExp("[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})");
input.forEach(function(x){
console.log(re.exec(x)[1])
});

Related

How to get the part of the string after the 2nd space [duplicate]

This question already has answers here:
Cutting a string at nth occurrence of a character
(5 answers)
Closed 1 year ago.
I am having a string like: $m-set 88829828277 very good he is. From this string I want to get the part after the second space. ie, I want to get: very good he is.
I tried using split(" ")[2] but it only gives one word: very.
Any help is greatly appreciated!
Thanks!
While you could split and join:
const input = '$m-set 88829828277 very good he is';
const splits = input.split(' ');
const output = splits.slice(2).join(' ');
console.log(output);
You could also use a regular expression:
const input = '$m-set 88829828277 very good he is';
const output = input.match(/\S+ \S+ (.+)/)[1];
console.log(output);
where the (.+) puts everything after the second space in a capture group, and the [1] accesses the capture group from the match.

JavaScript Regex Question. How to split this string [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 2 years ago.
I'm new to Regex and was wondering how to split this string s4://test-dev/prefixes/file.mxf into ['test-dev', 'prefixes/file.mxf']. I want it to work for an unknown file path.
Ex)
s4://test-dev/prefixes/file.mxf/newpath/anothernewpath into
['test-dev', 'prefixes/file.mxf/newpath/anothernewpath']
If you are using regex for splitting (which is not necessary) you can use this regex: s4:\/\/test-dev\/(.*) and use first group (first parentheses) as second string (first one is always same as i can see), but easiest way is to find position of third '/' with this var pos=str.split("/", i).join("/").length; and then find substring from that position to end: var res = str.substring(pos, str.length-pos);
Instead of splitting, use capture groups.
url.match(/^[^/]+:\/\/([^/]+)\/?(.*)/).slice(1)
Please check the code below:
let url = "s4://test-dev/prefixes/file.mxf/newpath/anothernewpath"
let match = url.match(/^s4:\/\/([\w-]+)\/(.+)$/)
let result = [match[1], match[2]]
console.log(result)
The result is:
[
"test-dev",
"prefixes/file.mxf/newpath/anothernewpath"
]
/^[\w+\:\/\/]+[-w+]/i
matches 'text-dev'
/w+\:\/\/[-w+]\/gi/
matches the rest

Spliting numbers out of a string contain characters and numbers [duplicate]

This question already has answers here:
Extract numbers from a string using javascript
(4 answers)
Closed 6 years ago.
I want to split the numbers out of a string and put them in an array using Regex.
For example, I have a string
23a43b3843c9293k234nm5g%>and using regex I need to get [23,43,3843,9293,234,5]
in an array
how can i achieve this?
Use String.prototype.match()
The match() method retrieves the matches when matching a string against a regular expression
Edit: As suggested by Tushar, Use Array.prototype.map and argument as Number to cast it as Number.
Try this:
var exp = /[0-9]+/g;
var input = "23a43b3843c9293k234nm5g%>";
var op = input.match(exp).map(Number);
console.log(op);
var text = "23a43b3843c9293k234nm5g%>";
var regex = /(\d+)/g;
alert(text.match(regex));
You get a match object with all of your numbers.
The script above correctly alerts 23,43,3843,9293,234,5.
see Fiddle http://jsfiddle.net/5WJ9v/307/

Extract specific data from JavaScript .getAttribute() [duplicate]

This question already has answers here:
Parse query string in JavaScript [duplicate]
(11 answers)
Closed 8 years ago.
So let's say I have this HTML link.
<a id="avId" href="http://www.whatever.com/user=74853380">Link</a>
And I have this JavaScript
av = document.getElementById('avId').getAttribute('href')
Which returns:
"http://www.whatever.com/user=74853380"
How do I extract 74853380 specifically from the resulting string?
There are a couple ways you could do this.
1.) Using substr and indexOf to extract it
var str = "www.something.com/user=123123123";
str.substr(str.indexOf('=') + 1, str.length);
2.) Using regex
var str = var str = "www.something.com/user=123123123";
// You can make this more specific for your query string, hence the '=' and group
str.match(/=(\d+)/)[1];
You could also split on the = character and take the second value in the resulting array. Your best bet is probably regex since it is much more robust. Splitting on a character or using substr and indexOf is likely to fail if your query string becomes more complex. Regex can also capture multiple groups if you need it to.
You can use regular expression:
var exp = /\d+/;
var str = "http://www.whatever.com/user=74853380";
console.log(str.match(exp));
Explanation:
/\d+/ - means "one or more digits"
Another case when you need find more than one number
"http://www.whatever.com/user=74853380/question/123123123"
You can use g flag.
var exp = /\d+/g;
var str = "http://www.whatever.com/user=74853380/question/123123123";
console.log(str.match(exp));
You can play with regular expressions
Well, you could split() it for a one liner answer.
var x = parseInt(av.split("=")[1],10); //convert to int if needed

How to remove all characters after a certain index from a string [duplicate]

This question already has answers here:
Remove everything after a certain character
(10 answers)
Closed 9 years ago.
I am trying to remove all characters from a string after a specified index. I am sure there must be a simple function to do this, but I'm not sure what it is. I am basically looking for the javascript equivalent of c#'s string.Remove.
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.split("$")[0];
or
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.substring(0, myStr.indexOf("$") - 1);
Use substring
var x = 'get this test';
alert(x.substr(0,8)); //output: get this
You're looking for this.
string.substring(from, to)
from : Required. The index where to start the extraction. First character is at index 0
to : Optional. The index where to stop the extraction. If omitted, it extracts the rest of the string
See here: http://www.w3schools.com/jsref/jsref_substring.asp
I'd recommend using slice as you can use negative positions for the index. It's tidier code in general. For example:
var s = "messagehere";
var message = s.slice(0, -4);

Categories