Currently I have a JavaScript program that is using Regex to detect UK postcodes.
At the minute it is just displaying them in an alert.
I am currently struggling to detect Postcodes with a space.
For example SW12 5BV, BR3 8DD
It also needs to accept Postcodes without spaces such as DE148NV, JN24HH.
Current Regex Code:
var postcodePattern = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i;
var resultPost = postcodePattern.test(words[i]);
if(resultPost) {
alert("Postcode detected: " + words[i]);
I have also tried various other UK postcode regex which to no avail.
Example
//var postcodePattern = /^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {0,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR ?0AA)$/
I also have a function which removes all HTML Tags after the regex has taken place which has affected previous regex.
removeHTMLTags: function(aString){
var strInputCode = aString;
var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, " ");
strTagStrippedText = strTagStrippedText.replace(/ /g," ");
//Remove some escape characters
strTagStrippedText = strTagStrippedText.replace(/\(|\)|\{|\}|\[|\]|\?|\*|\+|\||\//ig," ");
//Replace multilple white spaces with single white space
strTagStrippedText = strTagStrippedText.replace(/\s+/g," ");
return strTagStrippedText; },
Any help would be grateful.
As simple as putting your space inside a character class? I am assuming you are only allowing a single space based on the re-formatting code in the second code block.
var postcodePattern = /[A-Z]{1,2}[0-9]{1,2}[ ]{0,1}[0-9][A-Z]{2}/i;
var resultPost = postcodePattern.test(words[i]);
if(resultPost) {
alert("Postcode detected: " + words[i]);
As per the comments, you are splitting you input on spaces as well here:
bodyContentsStrippedTags.split(/\s+|\,|\&|\||\/|\?|\!|\:|;|"/);
with the \s+ in your split regex. This means postal codes with a space get passed to your regex as two separate array items and not a single string.
Related
I have read the solution on this post How do I split a string at a space after a certain number of characters in javascript?
And it works to a certain point. But what I am trying to achieve is slightly different.
I have a user input which has a 40 character limit. I am taking that input and displaying it on the screen. However, I need to split the input at around 20 characters and then insert the remainder on the next line. And it is only allowed to go on 2 lines max.
UPDATE:: I should also mention here that as well as displaying the text on the front end, we also need to pass the string to our backend. But instead of sending it with the <br/>, we need to insert \n to force the new line in our backend system.
Ultimately, each line cannot be over 20 characters. However, it needs to be dynamic, so that if the user inputs a string that is 30 characters, but the space comes before the 20th character, how can I adjust it so that it splits at a space before the 20th character? - I hope that makes sense.
For example
TEXT12345 STRING46789
Should appear like this
TEXT12345
STRING46789
but, also the following
TEXT STRING ABCDEF
NEW LINE HERE
Each line needs to be a maximum of 20 characters and I can't force hyphenation.
The below code is what I have done, but it doesn't work well as I often get 'undefined' before the space. Plus, its not dynamically looking for a space before the 20 character limit
Child1Name.keyup(function(e) {
var stringValue = Child1Name.val();
if (stringValue.length > 19) {
let [firstLine, secondLine] = stringValue.replace(/.{20}\S*\s+/g, "$&#").split(/\s+#/)
previewChild1Name.html(firstLine + "<br/>" + secondLine);
}else{
previewChild1Name.text(stringValue);
}
});
Any help here would be greatly appreciated.
You can write a function like below. First split your string with space and loop over it to append the word. If after appending a new word it surpasses the length then add existing word to arr and clear the current string.
Try the code below.
function getSplittedString(s, length) {
let arr = [];
let str = '';
s.split(' ').forEach(x => {
if (str !== '' && (str + ' ' + x).length > length) {
arr.push(str);
str = '';
}
str = (str + ' ' + x).trim();
});
if (str !== '') {
arr.push(str);
}
return arr.join('<br/>')
}
console.log(getSplittedString('TEXT12345 STRING46789', 20));
from what i have seen and found on this site:
mdn website
You can use split(on strings) like this on stringvalue(should be the entire string);
var stringvalue = 'TEXT12345 STRING46789';
var words = str.split(' '); // what charater need to cut the string
console.log(words[0]);
// expected output: "TEXT12345"
Sorry for the rushing the answer, kinda busy rn Hope this helps.
I am trying to create a regex that removes all text after a comma and the space+word after the comma.
So if I have the string:
"123 some address, place 2800 Australia"
I want to remove " 2800 Australia". The word "place" can be anything so the regex needs to match a word not the specified "place" string.
So far I have this as working best:
var s = '123 some address, place 2800 Australia';
s = s.substring(0, s.indexOf(', '));
document.write(s);
However this will of course also remove "place" and I need the first word after the comma to still be included.
Thanks!
You can do this by using split(), replace(), match() function with some ReGex - This was a bit tricky as i had to consider two commas scenarios as well.
First we can use match the commas in the string get the address only then you can use the get the place and split from the space " "
After that we can consider two commas scenario which will be after the place so we can check by using replace() and replace with nothing.
Lastly its not possible with using jQuery as jQuery is Javascript.
Having one comma
var text = '123 some address, place 2800 Australia';
//Match and get Address
var addr = text.match(/([^,]*)(.*)/)[1];
//Match and get place with split
var place = text.match(/([^,]*),(.*)/)[2].split(' ')[1]
//New Address
var newAdd = addr + ', ' + place
//Write
document.write(newAdd);
//Console.log
console.log(newAdd);
Having two commas (possibility)
The solution works for two commas as well.
var text = '123 some address, place, 2800 Australia';
//Match and get Address
var addr = text.match(/([^,]*)(.*)/)[1];
//Match and get place with split
var place = text.match(/([^,]*),(.*)/)[2].split(' ')[1]
//If two commas
var ifTwoCommas = place.replace(',', '');
//New Address
var newAdd = addr + ', ' + ifTwoCommas
//Write
document.write(newAdd);
//Console.log
console.log(newAdd);
I have a string Topic: Computer Science
And want to strip out topic: (but in fact I want this to work with any header on the string line) and return Computer Science.
I thought about splitting the components and then adding the spaces back in:
var subjectLine = thisLine.split(" ");
var subjectString = "";
for (i = 1; i < subjectLine.length; i++) {
subjectString += subjectLine[i] + " ";
}
But then I need to remove the last space from the string.
For each doesn't work as I need to NOT have the first element appended.
I'm not sure how to do this in js so it is reusable for many different lines and topic names that can come from the subjectLine
After splitting the line, remove the first element from the array, then join the rest back together.
var thisLine = "Topic: Computer Science";
var subjectLine = thisLine.split(" ");
subjectLine.splice(0, 1);
var subjectString = subjectLine.join(" ");
console.log(subjectString);
You might consider using a regular expression, it'll probably be a lot easier than working with arrays: match the non-space characters at the beginning of the string, followed by at least one space, and .replace with the empty string:
const subjectString = thisLine.replace(/^\S+\s+/, '');
const transform = line => line.replace(/^\S+\s+/, '');
console.log(transform('Topic: Computer Science'));
You need to know where the heading stops and the real data starts. Then delete all characters up to that point.
So, for instance, if you know that the heading ends with a colon, then do:
var line = "this is the topic: Computer Science";
var topic = line.replace(/^.*:\s*/, "");
console.log(topic);
I'm trying to build a text fixing page for normalising text written in all capital letters, all lower case or an ungrammatical mixture of both.
What I'm currently trying to do is write a regular expression to find all full stops, question marks and line breaks, then split the string in to various strings containing all of the words up to and including each full stop.
Then I'm going to wrap them with <span> tags and use CSS :first-letter and text-transform:capitalize; to capitalise the first letter of each sentence.
The last stage will be writing a dictionary function to find user-specified words for capitalisation.
This question only concerns the part about writing a regex and splitting in to strings.
I've tried too many methods to post here, with varying results, but here's my current attempt:
for(var i=0; i < DoIt.length; i++){
DoIt[i].onclick = function(){
var offendingtext = input.value.toString();
var keeplinebreaks = offendingtext.replace(/\r?\n/g, '<br />');
var smalltext = keeplinebreaks.toLowerCase();
//split at each character I specify
var breakitup = smalltext.split(/[/.?\r\n]/g);
breakitup.forEach(function(i){
var i;
console.log(i);
var packagedtogo = document.createElement('span');
packagedtogo.className = 'sentence';
packagedtogo.innerHTML = breakitup[i];
output.appendChild(packagedtogo);
i++;
});
}
}
It was splitting at the right places before, but it was printing undefined in the output area between the tags. I've been at this for days, please could someone give me a hand.
How can I split a string in to multiple string sentences, and then wrap each string with html tags?
Your regex for the split is fine. Just forgot to escape a few characters:
var str = "SDFDSFDSF?sdf dsf sdfdsf. sdfdsfsdfdsfdsfdsfdsfsdfdsf sdf."
str.split( (/[\.\?\r\n]/g))
//["SDFDSFDSF", "sdf dsf sdfdsf", " sdfdsfsdfdsfdsfdsfdsfsdfdsf sdf", ""]
Use for each iteration capabilities like this:
breakitup.forEach(function(element){
var packagedtogo = document.createElement('span');
packagedtogo.className = 'sentence';
packagedtogo.innerHTML = element;//breakitup is undefiend
output.appendChild(packagedtogo);
//No need to increase index
});
I have got a text area and a function that splits the pasted content based on the spaces between content elements and turns them into labels one by one:
Say I have the following content to be pasted:
1234,john smith,john#test.com 4312,jack gold,jack#yahoo.com 5678,Brian,brian#gmail.com
and obviously I use
$('#testArea').on("paste", ".maininput", function (event) {
var text = $(element).val();
var contentArray = text.split(" ");
}
The result should be 3 labels with the following format (users mobile number,full name, email)
But because of the fact that there are spaces between firstname and lastname I am not able to get the right result.
What I am trying to achieve is sort of escaping the spaces when its between first and last name.
has anyone got any idea how to do it?
Don't split on spaces. Instead, scan for what you want:
var s = "1234,john smith,john#test.com 4312,jack gold,jack#yahoo.com 5678,Brian,brian#gmail.com"
var lines = s.match(/\S[^,]+,[^,]+,[^ ]+/g)
for (var i=lines.length;i--;){
console.log(lines[i].split(','));
}
// ["5678", "Brian", "brian#gmail.com"]
// ["4312", "jack gold", "jack#yahoo.com"]
// ["1234", "john smith", "john#test.com"]
That regex says:
Find something other than whitespace
Followed by one or more things that are not a comma
Followed by a comma
Followed by one or more things that are not a comma
Followed by a comma
Followed by one or more things that are not a space
Better to use a regular expression to match the pattern.
var str = "1234,john smith,john#test.com 4312,jack gold,jack#yahoo.com 5678,Brian,brian#gmail.co";
var matchGroups = str.match(/([^,]*,[^,]*,[^ ]*)/g); //look for pattern "XXX,XXX,XXX" followed by whitespace or end of line
console.log(matchGroups);
//Now work with the sections
for( var i=0;i<matchGroups.length;i++){
var parts = matchGroups[i].split(","); //split it into your parts on commas
console.log(parts);
}
JSFiddle
you can run a for loop to check the next character of space, and based on it you can replace space with or leave it as it is. I mean if the next character is a number you can simply leave the space as it is and if it is a letter change space to
For example, replace <space><digit> with |<digit> and then split on |:
text.replace(/ (\d)/g, "|$1").split("|")
Example:
"1234,john smith,john#test.com 4312,jack gold,jack#yahoo.com 5678,Brian,brian#gmail.com".replace(/ (\d)/g, "|$1").split("|")
["1234,john smith,john#test.com",
"4312,jack gold,jack#yahoo.com",
"5678,Brian,brian#gmail.com"]
jQuery( window ).load(function() {
jQuery("#FullNametest").change(function(){
var temp = jQuery(this).val();
var fullname = temp.split(" ");
var firsname='';
var middlename='';
var lastname = '';
firstname=fullname[0];
lastname=fullname[fullname.length-1];
for(var i=1; i < fullname.length-1; i++)
{
middlename = middlename +" "+ fullname[i];
}
jQuery('#FirstName').val(firstname);
jQuery('#middlename').val(middlename);
jQuery('#LastName').val(lastname);
});
});