String operation in javascript - javascript

How can I get only 'ABCD' from string 'ABCD150117T15' in java script.
I would like strip rest of the string from 'ABCD' in this example and generally everything until but excluding the first number character.
thanks

You can match for a-z
'ABCD150117T15'.match(/^[a-z]+/i)
you can match anything that is not a number
'ABCD150117T15'.match(/^[^\d]+/)

Use regex then to match the first digit, and then subtring it to the text;
var str = 'ABCD150117T15';
var index = str.search(/\d/);
var text = str.substr(0,index);

'ABCD150117T15'.match(/^\D+/)[0]
This would give you everything until the first number then :)

Related

javascript replace text at second occurence of "/"

I have this string
"/mp3/mysong.mp3"
I need to do make this string look like this with javascript.
"/mp3/myusername/mysong.mp3"
My guess would be to find second occurrence of "/", then append "myusername/" there or prepend "/myusername" but I'm not sure how to do this in javascript.
Just capture the characters upto the second / symbol and store it into a group. Then replace the matched characters with the characters inside group 1 plus the string /myusername
Regex:
^(\/[^\/]*)
Replacement string:
$1/myusername
DEMO
> var r = "/mp3/mysong.mp3"
undefined
> r.replace(/^(\/[^\/]*)/, "$1/myusername")
'/mp3/myusername/mysong.mp3'
OR
Use a lookahead.
> r.replace(/(?=\/[^/]*$)/, "/myusername")
'/mp3/myusername/mysong.mp3'
This (?=\/[^/]*$) matches a boundary which was just before to the last / symbol. Replacing the matched boundary with /myusername will give you the desired result.
This works -
> "/mp3/mysong.mp3".replace(/(.*?\/)(\w+\.\w+)/, "$1myusername\/$2")
"/mp3/myusername/mysong.mp3"
Demo and explanation of the regex here
use this :
var str = "/mp3/mysong.mp3";
var res = str.replace(/(.*?\/){2}/g, "$1myusername/");
console.log(res);
this will insert the text myusername after the 2nd / .

Match a string between two other strings with regex in javascript

How can I use regex in javascript to match the phone number and only the phone number in the sample string below? The way I have it written below matches "PHONE=9878906756", I need it to only match "9878906756". I think this should be relatively simple, but I've tried putting negating like characters around "PHONE=" with no luck. I can get the phone number in its own group, but that doesn't help when assigning to the javascript var, which only cares what matches.
REGEX:
/PHONE=([^,]*)/g
DATA:
3={STATE=, SSN=, STREET2=, STREET1=, PHONE=9878906756,
MIDDLENAME=, FIRSTNAME=Dexter, POSTALCODE=, DATEOFBIRTH=19650802,
GENDER=0, CITY=, LASTNAME=Morgan
The way you're doing it is right, you just have to get the value of the capture group rather than the value of the whole match:
var result = str.match(/PHONE=([^,]*)/); // Or result = /PHONE=([^,]*)/.exec(str);
if (result) {
console.log(result[1]); // "9878906756"
}
In the array you get back from match, the first entry is the whole match, and then there are additional entries for each capture group.
You also don't need the g flag.
Just use dataAfterRegex.substring(6) to take out the first 6 characters (i.e.: the PHONE= part).
Try
var str = "3={STATE=, SSN=, STREET2=, STREET1=, PHONE=9878906756, MIDDLENAME=, FIRSTNAME=Dexter, POSTALCODE=, DATEOFBIRTH=19650802, GENDER=0, CITY=, LASTNAME=Morgan";
var ph = str.match(/PHONE\=\d+/)[0].slice(-10);
console.log(ph);

Matching everything after first pipe character in Javascript RegEx

I have this string:
"http://www.yahoo.com/abc/123|X|Y|Z"
I need to get everything after the first pipe with a regex. So I would want to be left with this string:
"X|Y|Z"
How do I do this in JavaScript?
Using a simpler regex /\|(.*)/
var str = "http://www.yahoo.com/abc/123|X|Y|Z";
var aryMatches = str.match(/\|(.*)/);
// aryMatches[1] will have your results
regex explaination
Converting my comment to an answer:
Shockingly, regexes are not the answer to everything.
> xkcd
Try this:
str.split("|").slice(1).join("|");
This splits your string on pipe characters, slices off the first item, then joins the rest with pipes again.
First group contains the expected characters,
^.*?\|(.*)$
DEMO
You can use this regex:
/^[^|]*\|(.*)/
And use matched group #1 for your match.
Forget the splitting and splicing, just use a substring
var str = "http://www.yahoo.com/abc/123|X|Y|Z";
str.substr(str.indexOf("|") + 1);

Extract number between slashes

This is my setup:
var test =
"http://tv.website.com/video/8086844/randomstring/".match(/^.+tv.website.com\/video\/(.*\d)/);
I want to extract the video id(8086844) and the regex does work, however when another digit is added after the "randomstring", it also matches the 8086844 + randomstring + other number.
What do I have to change in order to always get just the video id.
Try this regex
/^.+tv.website.com\/video\/([\d]+)/
It will search every digit character after ...video\ word and then give all the concordant digits thereafter till any non-digit character comes
The problem is the (.*\d) part, it looks for a greedy string ends with a digit, instead you need a continues series of digits after video/, it can be done via (\d+)
change it to
var test = "http://tv.website.com/video/8086844/randomstring/dd".match(/^.+tv.website.com\/video\/(\d+)/)[1];
var test = "http://tv.website.com/video/8086844/randomstring/8";
test = test.match(/^.+tv.website.com\/video\/(\d+)/);
console.log(test);
console.log(test[1]);
Output
[ 'http://tv.website.com/video/8086844',
'8086844',
index: 0,
input: 'http://tv.website.com/video/8086844/randomstring/8' ]
8086844
You are almost there. We know that, its going to be only numbers. So instead of .*\d we are gathering only the digits and grouping them using parens.
This is the simplest of all:
Use substr here
test.substr(28,7)
Fiddle
To extract out the id from your string test:We use substr(from,to)

getting contents of string between digits

have a regex problem :(
what i would like to do is to find out the contents between two or more numbers.
var string = "90+*-+80-+/*70"
im trying to edit the symbols in between so it only shows up the last symbol and not the ones before it. so trying to get the above variable to be turned into 90+80*70. although this is just an example i have no idea how to do this. the length of the numbers, how many "sets" of numbers and the length of the symbols in between could be anything.
many thanks,
Steve,
The trick is in matching '90+-+' and '80-+/' seperately, and selecting only the number and the last constant.
The expression for finding the a number followed by 1 or more non-numbers would be
\d+[^\d]+
To select the number and the last non-number, add parens:
(\d+)[^\d]*([^\d])
Finally add a /g to repeat the procedure for each match, and replace it with the 2 matched groups for each match:
js> '90+*-+80-+/*70'.replace(/(\d+)[^\d]*([^\d])/g, '$1$2');
90+80*70
js>
Or you can use lookahead assertion and simply remove all non-numerical characters which are not last: "90+*-+80-+/*70".replace(/[^0-9]+(?=[^0-9])/g,'');
You can use a regular expression to match the non-digits and a callback function to process the match and decide what to replace:
var test = "90+*-+80-+/*70";
var out = test.replace(/[^\d]+/g, function(str) {
return(str.substr(-1));
})
alert(out);
See it work here: http://jsfiddle.net/jfriend00/Tncya/
This works by using a regular expression to match sequences of non-digits and then replacing that sequence of non-digits with the last character in the matched sequence.
i would use this tutorial, first, then review this for javascript-specific regex questions.
This should do it -
var string = "90+*-+80-+/*70"
var result = '';
var arr = string.split(/(\d+)/)
for (i = 0; i < arr.length; i++) {
if (!isNaN(arr[i])) result = result + arr[i];
else result = result + arr[i].slice(arr[i].length - 1, arr[i].length);
}
alert(result);
Working demo - http://jsfiddle.net/ipr101/SA2pR/
Similar to #Arnout Engelen
var string = "90+*-+80-+/*70";
string = string.replace(/(\d+)[^\d]*([^\d])(?=\d+)/g, '$1$2');
This was my first thinking of how the RegEx should perform, it also looks ahead to make sure the non-digit pattern is followed by another digit, which is what the question asked for (between two numbers)
Similar to #jfriend00
var string = "90+*-+80-+/*70";
string = string.replace( /(\d+?)([^\d]+?)(?=\d+)/g
, function(){
return arguments[1] + arguments[2].substr(-1);
});
Instead of only matching on non-digits, it matches on non-digits between two numbers, which is what the question asked
Why would this be any better?
If your equation was embedded in a paragraph or string of text. Like:
This is a test where I want to clean up something like 90+*-+80-+/*70 and don't want to scrap the whole paragraph.
Result (Expected) :
This is a test where I want to clean up something like 90+80*70 and don't want to scrap the whole paragraph.
Why would this not be any better?
There is more pattern matching, which makes it theoretically slower (negligible)
It would fail if your paragraph had embedded numbers. Like:
This is a paragraph where Sally bought 4 eggs from the supermarket, but only 3 of them made it back in one piece.
Result (Unexpected):
This is a paragraph where Sally bought 4 3 of them made it back in one piece.

Categories

Resources