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);
Related
Hi I have a text something like
"Welcome back ##Firstname ##Lastname. You Last accessed on ##Date"
My objective is to replace these tokens with actual values.
So what i did was
var str = "Welcome back ##Firstname ##Lastname. You Last accessed on ##Date;
var data = str.split('#');
My idea was - once i do this, my data will have an array of values something like
["Welcome back", "#FirstName" , "#LastName", "You Last accessed on" , "#Date"]
Once i have this, i can easily replace the tokens because i will know which one are properties and which one are static string. But fool i am since JS has other ideas.
it instead split it as :
["Welcome back ", "", "Firstname ", "", "Lastname. You Last accessed on ", "", "Date"]
What am i doing wrong? or what is the best way to replace tokens in a string?
I looked here. Did not like the approach much. Not a fan of curly brackets. would like to do it the "#" way - Since it will be easy for Content authors
Another regex option, split on /#(#\w+)[^\w#]+/, captures the name part while throwing off the first #, assuming the name identifiers are always made up of word characters:
var str = "Welcome back ##Firstname ##Lastname. You Last accessed on ##Date;"
var data = str.split(/#(#\w+)[^\w#]+/);
console.log(data.filter(s => s !== ""));
You can split "#" characters which are followed by "#" characters
var str = "Welcome back ##Firstname ##Lastname. You Last accessed on ##Date";
var res = str.split(/#(?=#)/);
console.log(res);
you can replace the '##' by some character followed by '#' like ',#' and then replace on that new character.
var str = "Welcome back ##Firstname ##Lastname. You Last accessed on ##Date";
var data = str.replace(/##/g, ',#').split(',');
console.log(data);
As your delemiters end with a space, may split by space:
.split(" ")
And then iterate and replace all words beginning with ##
var replaceBy={
lastname:"Doe",
name:"John"
}
var result= input.split(" ").map(function(word){
if(word[0]=="#" && word[1]=="#"){
return replaceBy[word.substr(2)] || "error";
}
return word:
}).join(" ");
However, it might be easier to suround your identifiers with delemiters e.g.:
Hi ##lastname##!
So you can do
.split("##")
And every second element is automatically an identifier.
Do this:
data = str.replace("##Firstname", "Robert").replace("##Lastname","Polson").replace('##Date','yesterday') ;
I have a Address like
Address : 273A-84, Sundharam Street,, Ganthi Path, Kovai,,,,India,641001
If string has more than 2 commas i want to replace with single comma.
In above address next to street and next to kovai there is multiple commas.I want to replace with single comma.
My expected output is:
Address : 273A-84, Sundharam Street,Ganthi Path,Kovai,India,641001
Please suggest regular expression.
var str = "Address : **273A-84, Sundharam Street,, Ganthi Path, Kovai,,,,India,641001**";
str.replace(/\,{1,}/gi, ',');
DEMO:http://jsbin.com/sejuma/2/
You can try this:-
var str="Address : 273A-84, Sundharam Street,, Ganthi Path, Kovai,,,,India,641001 ";
res = str.replace(/^[, ]+|[, ]+$|[, ]+/g, ",").trim();
alert("{" + res+ "}");
I have the following string of text:
textString1:textString2:textString3:textString4
I'm looking to capture each text string and assign them to variables.
I've somehow managed to come up with the following:
var errorText = 'AAAA:BBBB:CCCC:DDDD';
var subString, intro, host, priority, queue = '';
var re = /(.+?\:)/g;
subString = errorText.match(re);
intro = subString[0];
host = subString[1];
priority = subString[2];
//queue = subString[3];
console.log(intro + " " + host + " " + priority);
JS Bin Link
However, I'm having problems with:
capturing the last group, since there is no : at the end
the variables contain : which I'd like to strip
You don't need a regex for this - just use errorText.split(':') to split by a colon. It will return an array.
And if you then want to add them together with spaces, you could do a simple replace instead: errorText.replace(/:/g,' ').
use split method for this.it will return array of string then iterate through array to get string:
var errorText = 'AAAA:BBBB:CCCC:DDDD';
var strArr=errorText.split(':');
console.log(errorText.split(':'));
for(key in strArr){
console.log(strArr[key]);
}
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);
});
});
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.