Change javascript regex divider character - javascript

I have a simple JS question.
I have this code, and what I need is cut the textbox value every two characters (this works fine), but I want to change the comma with the column.
My actual result is:
stringtest - st,ri,ng,te,st
and I want this:
stringtest - st:ri:ng:te:st
my code is:
function test() {
var textboxtext= $("#textbox").val();
var splitted = textboxtext.match(/.{2}|.{1,2}/g);
alert("B8:27:EB:" + splitted)

The problem is not with the regex, but with how you're converting the result array to a string. When the JavaScript engine needs to convert an array to a string (which is done implicitly when you use the binary + operator with an string on either side), it calls the toString() method, which basically just calls the join() method, which returns a string with each element of the array converted to a string, and separated by commas.
But you can call the join method yourself and specify what character you'd like it to use as a separator, like this:
alert("B8:27:EB:" + splitted.join(':'));
On a side note, you can simplify your regex to .{1,2}, which is exactly the same as what you had previously:
var splitted = textboxtext.match(/.{1,2}/g);

Related

How to get substring between two same characters in JavaScript?

I have a string value as abc:language-letters-alphs/EnglishData:7844val: . I want to extract the part language-letters-alphs/EnglishData, the value between first : and second :. Is there a way to do it without storing each substrings on different vars? I want to do it the ES6 way.
You can do this two ways easily. You can choose what suits you best.
Using String#split
Use split method to get your desired text.
The split() method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call.
let str = 'abc:language-letters-alphs/EnglishData:7844val:'.split(':')
console.log(str[1]) //language-letters-alphs/EnglishData
Using String#slice
You can use [ Method but in that you have define the exact indexes of the words you want to extract.
The slice() method extracts a section of a string and returns it as a new string, without modifying the original string.
let str = 'abc:language-letters-alphs/EnglishData:7844val:'
console.log(str.slice(4, 38)) //language-letters-alphs/EnglishData
const str = "abc:language-letters-alphs/EnglishData:7844val:"
const relevantPart = str.split(':')[1]
console.log("abc:language-letters-alphs/EnglishData:7844val:".split(":")[1])

Javascript regexp (match after ":" symbol)

How to get all text following the symbol ":"?
I have tried:
'prop:bool*'.match(/:(.[a-z0-9]+)/ig)
But it returns [":bool"] not ["bool"].
Update:
I need to use this inside the following expression:
'prop:bool*'.match(/^[a-z0-9]+|:.[a-z0-9]+|\*/ig);
So that the result becomes:
["prop", "bool", "*"]
You could solve this by performing a positive lookbehind action.
'prop:bool*'.match(/^[a-z0-9]+|(?<=:).[a-z0-9]+|\*/ig)
The positive lookbehind is the (?<=:) part of the regex and will here state a rule of must follow ':'.
The result should here be ["prop", "bool", "*"].
Edit:
Original requirements were somewhat modified by original poster to return three groups of answers. My original code, returning one answer, was the following:
'prop:bool*'.match(/(?<=:).[a-z0-9]+/ig)
This is not a pure regex solution since it takes advantage of the String Object with its substring() method, as follows:
var str = 'prop:bool*';
var match = str.match(/:(.[a-z0-9]+)/ig).pop().substring(1,str.length);
console.log(match);
When the match is successful, an array of one element will hold the value :bool. That result just needs to have the bool portion extracted. So, the element uses its pop() method to return the string value. The string in turn uses its substring() method to bypass the ':' and to extract the desired portion, namely bool.
var [a,b,c] = 'prop:bool*'.match(/^([a-z0-9]+)|:(.[a-z0-9]+)|(\*)/ig);
console.log(a,b.substring(1,b.length),c);
To return three groups of data, the code uses capture groups and trims off the colon by using the substring() method of b.
You could simply do:
'prop:bool*'.match(/:(.[a-z0-9]+)/)[1]
If your entire string is of the form you show, you could just use a regex with capture groups to get each piece:
console.log('prop:bool*'.match(/^([a-z0-9]+):(.[a-z0-9]+)(\*)/i).slice(1));

JavaScript strings manipulations

I have a string like this below:
var stOrig= "ROAM-Synergy-111-222-LLX" ;
There can be any no. of "alphabetic" terms before numeric values 111-222..
There may or may not be any numeric values i.e the string can also be simply like this:
"ROAM-Synergy-LCD-ROAM".
if there are numeric values then I am using this
var myval = st.match(/^\D+(?=-)/)[0];
to get only the alphabetic terms before the numeric values. Its working fine till here.
But if suppose string does not contains any numeric values then my regular expression returns one less term i.e
Say the original string is: "ROAM-Synergy-LCD-ROAM" (without any numbers in it.)
Now if is use above reg expression...then it will return only "ROAM-Synergy-LCD"
..
so first I need to check for any numeric values in original string.. and if string contains numeric values then I use above reg exp...but please suggest If string does not contain numeric values then what reg expression to use..
Use
var myval = st.match(/^\D+(?=-|$)/)[0];
The $ matches at the end of the string.
See it live on regex101.com.

How to remove double quotes from jquery array

I have a variable which contains the values like this ..
["09:09:49", "00:14:09", "00:05:50", "02:38:02", "01:39:28"]
Now as per my need i have to formate like this ..
[09:09:49, 00:14:09, 00:05:50, 02:38:02, 01:39:28]
for this i tried
callduration=[];
callduration=["09:09:49", "00:14:09", "00:05:50", "02:38:02", "01:39:28"];
var newstring = callduration.replace(/\"/g,'');
But it is giving error ..
TypeError: callduration.replace is not a function
var newstr=callduration.replace(/\"/g,'');
Please help me.
Thanks in advance..
First off, you must note that callduration is an array. Arrays do not have a replace method, hence the error.
As mentioned by #Felix Kling, the quotes are just string delimiters. They are not part of the string values contained in your array of strings. For example, when accessing callduration[0] you will get a string containing the 09:09:49 sequence of characters.
However, if you really need a string in the requested format, here it is:
var callduration = ["09:09:49", "00:14:09", "00:05:50", "02:38:02", "01:39:28"];
var newstr = '[' + callduration.join(', ') + ']';
newstr; //"[09:09:49, 00:14:09, 00:05:50, 02:38:02, 01:39:28]"
Though this probably won't be of much use unless you have some very specific use case in mind.
callduration is an array. That means it contains a sequential, ordered list of items. Those items must be something that can exisdt in javascript. As your array exists like this:
["09:09:49", "00:14:09", "00:05:50", "02:38:02", "01:39:28"]
it is an array of strings. Each time value is represented by its own string. The quote marks are not actually part of the string - that' just how a string is represented when typing it.
If you want the array to be an array of something other than strings, you would need to specify what data type you want it to be. 09:09:49 as you've asked, it not a legal javascript piece of data.
Some choices that you could use:
An array of numbers where each number represents a time value (say milliseconds since midnight).
An array of Date objects.
If you have an array of strings now and you wanted to convert it to either of the above, you would loop through your existing array, parse the string you have now into an actual numeric time and then convert that into whatever numeric or object format you want to be in the array.

Cut out, and replace a part of a string

There is a part in my string from, to which I would like to replace to an another string replace_string. My code should work, but what if there is an another part like the returned substring?
var from=10, to=17;
//...
str = str.replace(str.substring(from, to), replace_string);
For example:
from=4,to=6
str = "abceabxy"
replace_string = "zz"
the str should be "abcezzxy"
What you want to do is simple! Cut out and replace the string. Here is the basic tool, you need scissor and glue! Oops I mean string.Split() and string.Replace().
How to use?
Well I am not sure if you want to use string.Split() but you have used string.Replace() so here goes.
String.Replace uses two parameters, like this ("one", "two") what you need to make sure is that you are not replacing a char with a string or a string with a char. They are used as:
var str="Visit Microsoft!";
var n=str.replace("Microsoft","W3Schools");
Your code:
var from=10, to=17;
//...
var stringGot = str.replace(str.substring(from, to), replace_string);
What you should do will be to split the code first, and then replace the second a letter! As you want one in your example. Thats one way!
First, split the string! And then replaced the second a letter with z.
For String.Replace refer this: http://www.w3schools.com/jsref/jsref_replace.asp
For String.SubString: http://www.w3schools.com/jsref/jsref_substring.asp
For String.Split: http://www.w3schools.com/jsref/jsref_split.asp
Strings are immutable. This means they do not change after they are first instantiated. Every method to manipulate a string actually returns a new instance of a string. So you have to assign your result back to the variable like this:
str = str.replace(str.substring(from, to), replace_string);
Update: However, the more efficient way of doing this in the first place would be the following. it is also less prone to errors:
str = str.substring(0, from) + replace_string + str.substring(to);
See this fiddle: http://jsfiddle.net/cFtKL/
It runs both of the commands through a loop 100,000 times. The first takes about 75ms whereas the latter takes 20ms.

Categories