I am trying to split a UK postcode string to only include the initial letters. For example, 'AA1 2BB' would become 'AA.'
I was thinking something like the below.
var postcode = 'AA1 2BB';
var postcodePrefix = postcode.split([0-9])[0];
This does not actually work, but can someone help me out with the syntax?
Thanks for any help.
You can try something like this:
var postcode = 'AA1 2BB';
var postcodePrefix =postcode.split(/[0-9]/)[0];
Alternatively, you could use a regex to simply find all alphabetic characters that occur at the beginning of the string:
var postcode = 'AA1 2BB';
var postcodePrefix = postcode.match(/^[a-zA-Z]+/);
If you want any initial characters that are non numeric, you could use:
var postcodePrefix = postcode.match(/^[^0-9]+/);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
"AA1 2BB".split(/[0-9]/)[0];
or
"AA1 2BB".split(/\d/)[0];
var m = postcode.match(/([^\d]*)/);
if (m) {
var prefix = m[0];
}
Related
Hi i am try to find a variable date in a string with a regex and after this i want to save the date in a new variable my code looks like:
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
if(valide.test(text) === true){
}
how can i put the found date (02.02.1989) in a new variable
You can create groups in your Regex expression (just put the values you want between parenthesis) and then use this to get the specific group value.
Note, however, I think your regex is wrong... it seems you end with 1 plus 4 digits
You can use match on a string:
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
console.dir(text.match(valide)) // ["02.02.1989"]
if(valide.test(text) === true){
}
Using REGEXP function match you can extract the part that match your regular expression.
After this you will get an object. In this case i turn it into a string so you can do a lot more things with it.
var myDate = text.match(valide).toString();
Hope this helps :>
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
if(valide.test(text) === true){
var myDate = text.match(valide).toString();
console.log(myDate)
}
You can use match for that:
var valide =new RegExp(/\d{2}([./-])\d{2}\1\d{4}$/mg);
var text = 'lalaahfdsdfl 02.02.1989';//example
var foundDate = text.match(valide);
console.log(foundDate);
Also, you can make the regex a bit simpler if you switch the ([./-]) to ([-.]), because - is considered a literal match if it comes first inside a character class.
You could do something like this.
var result = text.match(valide)
Here is a reference for the match method String.prototype.match
Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);
I'm new to regex. I got a prob here. I work with xpaths strings. I want to remove a particular element from xpath string if the element has id = myVar
Example:
/html/body/div[3]/div[20]/section[1]/p[5]/span[1][#id="var645932"]/span
I want to replace the /span[1][#id="var645932"]/ with just / if my variable value is equal to id value i.e var645932
I need to do it in javascript. all are strings. I prefer regex. if any regex experts are there Kindly help. am stuck here. is it possible to accomplish it without regex ??
Any help are highly appreciated :) TIA
Try this:
var input = '/html/body/div[3]/div[20]/section[1]/p[5]/span[1][#id="var645932"]/span';
var regex = /\w+\[\w+\]\[\#id="var645932"\]\//gi;
input = input.replace(regex, '');
console.log(input);
Example fiddle
This regex is designed to work even if the structure of the HTML changes, eg:
var input = '/html/body/div[3]/div[20]/section[1]/div[6][#id="var645932"]/span';
If you need to set the id in the regex programmatically, use this:
var regex = new RegExp('/\w+\[\w+\]\[\#id="' + id + '"\]\//', 'gi');
You can use below code -
var expr = '/html/body/div[3]/div[20]/section[1]/p[5]/span[1][#id="var645932"]/span';
var idVal = "var645932";
expr = expr.replace('span[1][#id="'+idVal+'"]/','');
DEMO
Well, you could do it in the following way
var id = "var645932";
var regx = new RegExp('/[^/]+?\\[#id="' + id + '"]/');
var str = '/html/body/div[3]/div[20]/section[1]/p[5]/span[1][#id="var645932"]/span';
console.log(str.replace(regx, "/"));
Given the following patterns:
"profile[foreclosure_defenses_attributes][0][some_text]"
"something[something_else_attributes][0][hello_attributes][0][other_stuff]"
I am able to extract the last part using non-capturing groups:
var regex = /(?:\w+(\[\w+\]\[\d+\])+)(\[\w+\])/;
str = "profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]";
match = regex.exec(str);
["profile[foreclosure_defenses_attributes][0][properties_attributes][0][other_stuff]", "[properties_attributes][0]", "[other_stuff]"]
However, I want to be able to get everything but the last part. In other words, everything but [some_text] or [other_stuff].
I cannot figure out how to do this with noncapturing groups. How else can I achieve this?
Something like?
shorter, and matches from the back if you can have more of the [] items.
var regex = /(.*)(?:\[\w+\])$/;
var a = "something[something_else_attributes][0][hello_attributes][0][other_stuff11][other_stuff22][other_stuff33][other_stuff44]".match(regex)[1];
a;
or using replace, though less performant.
var regex = /(.*)(?:\[\w+\])$/;
var a = "something[something_else_attributes][0][hello_attributes][0][other_stuff11][other_stuff22][other_stuff33][other_stuff44]".replace(regex, function(_,$1){ return $1});
a;
If those really are your strings:
var regex = /(.*)\[/;
I have
"id": 1468306
inside of a string, how can I use regular expression to get the number 1468306 for it?
You can use this regex:
/: (\d+)/
as in:
s = '"id": 1468306';
r = /: (\d+)/;
console.log(r.exec(s)[1]);
Output:
1468306
you can use parseInt() method in javascript as follows:
var str = parseInt(id);
Following code may help you:
var input = '"id": 1468306';
var matches = input.match(/"id": (\d+)/);
var id = matches[1];
The id get the required number.
JSON.parse("{" + yourString + "}").id
Will be your number if you have that in a String.
Fiddle: http://jsfiddle.net/SfeMh/
var regEx = /\d+/g;
var str = '"id": 1468306';
var numbers = str.match(regEx);
alert(numbers); // returns 1468306
It looks like you're trying to parse a JSON String. Try this way as already mentioned:
var parsedObj = JSON.parse(myJSONString);
alert(parsedObj.id); // returns 1468306
This will match in this cases
id : 156454;
id :156454;
id:156454;
/id\s?[:]\s?[0-9]+/g.match(stringhere)
Alright, my JSON answer still stands, use it if that's your full string you're giving us in the question. But if you really want a regex, here's one that will search for "id" and then find the number after.
parseInt(yourString.match(/("id"\s?:\s?)(\d+)/)[2])
Fiddle: http://jsfiddle.net/tS9M4/