javascript replace tokens using string split - javascript

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') ;

Related

How can I cut the word after certain symbols?

I have such a structure "\"item:Test:3:Facebook\"" and I need somehow fetch the word Facebook.
The words can be dynamic. So I need to get word which is after third : and before \
I tried var arr = str.split(":").map(item => item.trim()) but it doesn't do what I need. How can I cut a word that will be after third : ?
A litte extra code to remove the last " aswell.
var str = "\":Test:3:Facebook\"";
var arr = str.split(":").map(item => item.trim());
var thirdItem = arr[3].replace(/[^a-zA-Z]/g, "");
console.log(thirdItem);
If the amount of colons (:) doesn't vary you can simply use an index on the resulting array like this:
var foo = str.split(":")[3];
The word after the 3rd : will be the fourth word returned, so it will be at index 3 in the array returned by split() (arrays being zero-indexed, of course). You might also want to get rid of the trailing quote mark.
Demo:
str = "\"item:Test:3:Facebook\"";
var word = str.split(":")[3].replace("\"", "");
console.log(word);
This should do the trick, plus remove all symbols
var foo = str.split(":")[3].replace(/[^a-zA-Z ]/g, "")

Capturing String Segments between Special Characters using Regular Expressions

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]);
}

javascript split when space but not always

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);
});
});

Remove special character from the starting of a string and search # symbol.in javascript

I want to remove special characters from the starting of the string only.
i.e, if my string is like {abc#xyz.com then I want to remove the { from the starting. The string shoould look like abc#xyz.com
But if my string is like abc{#xyz.com then I want to retain the same string as it is ie., abc{#xyz.com.
Also I want to check that if my string has # symbol present or not. If it is present then OK else show a message.
The following demonstrates what you specified (or it's close):
var pat = /^[^a-z0-9]*([a-z0-9].*?#.*?$)/i; //pattern for optional non-alphabetic start followed by alphabetic, followed by '#' somewhere
var testString = "{abc#xyz.com"; //Try with {abcxyz.com for alert
arr = pat.exec(testString);
var adjustedString;
if (arr != null) { adjustedString = arr[1]; } //The potentially adjustedString (chopped off non-alphabetic start) will be in capture group 1
else { adjustedString = ""; alert(testString + " does not conform to pattern"); }
adjustedString;
I have used two separate regex objects to achieve what you require .It checks for both the conditions in the string.I know its not very efficient but it will serve your purpose.
var regex = new RegExp(/(^{)/);
var regex1 = new RegExp(/(^[^#]*$)/);
var str = "abc#gmail.com";
if(!regex1.test(str)){
if(regex.test(str))
alert("Bracket found at the beginning")
else
alert("Bracket not found at the beginning")
}
else{
alert("doesnt contain #");
}
Hope this helps

split string based on a symbol

I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.

Categories