How to get the string value after the colon? - javascript

I really need your help,
How can I check a string to see if it has a ":" and then if it does, to get the string value after the ":"
ie.
var x = "1. Search - File Number: XAL-2017-463288"
var y = "XAL-2017-463288"

//check for the colon
if (x.indexOf(':') !== -1) {
//split and get
var y = x.split(':')[1];
}

Split on the colon, and grab the second member of the result. This assumes you want the first colon found.
var y = x.split(":")[1];
If the string didn't have a :, then y will be undefined, so a separate check isn't needed.
Or you could use .indexOf(). This assumes there's definitely a colon. Otherwise you'll get the whole string.
var y = x.slice(x.indexOf(":") + 1);
If you wanted to check for the colon, then save the result of .indexOf() to a variable first, and only do the .slice() if the index was not -1.

Related

Select string before some letters

If I have
var x = "3558&Hello world!&538345";
Now for selecting after I can use:
var y = x.split("&");
But I want to know can I select it before some char?
I need to get var z = 3558...
I don't want to select letters and nums from 0 to 4 because I don't know what is the length of numbers.... So is there any way to say select all before & ?
You're using the split functionality, so just grab the value at position 0 of the resulting array, that will be the substring up until the first &.
var y = x.split ("&")[0];
try this:
var y = x.split('&')[0]; // y = "3558"
You can use String.prototype.replace() with RegExp /&.+/ to match "&" and characters that follow, replace match with empty string
var z = "3558&Hello world!&538345".replace(/&.+/, "")
Lots of options! :D
function bySplit (textStr, delimiterStr) {
return textStr.split(delimiterStr)[0]
}
function byRegexReplace (textStr, delimiterStr) {
return textStr.replace(new RegExp(delimiterStr+'.*'), '')
}
function byRegexExec (textStr, delimiterStr) {
return (new RegExp('^(.*)'+delimiterStr)).exec(textStr)[1]
}
You could also write for or while loop to add chars to a result unless they encounter a matching delimiterStr, but they get messy compared to these three.

Comparison of back references in javascript regex

var x = "SomeText http://g.com";
var y = x.replace(/<a href="([^"]+)">([^<]+)<\/a>/igm, ('$2' == '$1')?"t":"f");
The comparison is returning false. And y is now "SomeText f".
How do I compare and get "SomeText t" ? Am I missing something in the condition ?
Printing both the back references prints the same string.
var y = x.replace(/<a href="([^"]+)">([^<]+)<\/a>/igm, '($2)($1)')
This prints the same url for both back references.
The only time that JS will do anything special with a string like $1 or $2 is if it is part of the resulting string passed as the second argument to .replace().
What you have as '$2' === '$1' was saying if the string "$2" is the same as the string "$1", which is clearly always false.
Instead, what you can do is use the .match() method to get the various backreferences as an array which you can index into.
Try the following:
var x = "SomeText http://g.com";
var regex = /<a href="([^"]+)">([^<]+)<\/a>/igm;
var matches = x.match(regex);
var y = x.replace(regex, matches[2] == matches[1]?"t":"f");

Extract number with decimals in string (Javascript)

i have this kind of string:
COMC1.20DI
I need to extract, in this case "1.20", but number can have decimals or not. How can I do it? I also need to get the start and end position of the number.
For starting position, I found
value.search(/\d/);
But I can't get any code to work for getting the last position of the number.
How can I do this?
This worked for me when I tried:
var value = 'COMC120DI';
alert(value.match(/[\d\.]+/g)[0]);
This returned "120". If you have multiple numbers in your string, it will only return the first. Not sure if that's what you want. Also, if you have multiple decimal places, it'll return those, too.
This is how I extracted numbers (with decimal and colon) from a string, which will return numbers as an array.
In my case, it had undefined values in the result array so I removed it by using the filter function.
let numArr = str.match(/[\d\.\:]+/g).map(value => { if (value !='.' && value !=':'){ return value } })
numArr = numArr.filter(function( element ) {
return element !== undefined;
});
You could try this snippet.
var match = text.match(/\d+(?:\.\d+)?/);
if (match) {
var result = 'Found ' + match[0] + ' on position ' + match.index + ' to ' + (match.index + match[0].length));
}
Note that the regex I'm using is \d+(?:\.\d+)?. It means it won't mistakenly check for other number-and-period format (i.e., "2.3.1", ".123", or "5.") and will only match integers or decimals (which is \d+ with optional \.\d+.
Check it out on JSFiddle.
var decimal="sdfdfddff34561.20dfgadf234";
var decimalStart=decimal.slice(decimal.search(/(\d+)/));
var decimalEnd=decimalStart.search(/[^.0-9]/);
var ExtractedNumber= decimalStart.slice(0,decimalEnd);
console.log(ExtractedNumber);
shows this in console: 34561.20
For extraction u can use this RegEx:
^(?<START>.*?)(?<NUMBER>[0-9]{1,}((\.|,)?[0-9]{1,})?)(?<END>.*?)$
The group "START" will hold everything before the number, "NUMBER" will hold any number (1| 1,00| 1.0) and finally "END" will hold the rest of the string (behind the number). After u got this 3 pieces u can calculate the start and end position.

how to retrieve a string between to same charecter

I know how to use substring() but here I have a problem, I'd like to retrieve a number between two "_" from a unknown string length. here is my string for example.
7_28_li
and I want to get the 28. How can I proceed to do so ?
Thanks.
Regex
'7_28_li'.match(/_(\d+)_/)[1]
The slashes inside match make it's contents regex.
_s are taken literally
( and ) are for retrieving the contents (the target number) later
\d is a digit character
+ is "one or more".
The [1] on the end is accesses what got matched from the first set of parens, the one or more (+) digits (\d).
Loop
var str = '7_28_li';
var state = 0; //How many underscores have gone by
var num = '';
for (var i = 0; i < str.length; i++) {
if (str[i] == '_') state++;
else if (state == 1) num += str[i];
};
num = parseInt(num);
Probably more efficient, but kind of long and ugly.
Split
'7_28_li'.split('_')[1]
Split it into an array, then get the second element.
IndexOf
var str = "7_28_li";
var num = str.substring(str.indexOf('_') + 1, str.indexOf('_', 2));
Get the start and end point. Uses the little-known second parameter of indexOf. This works better than lastIndexOf because it is guaranteed to give the first number between _s, even when there are more than 2 underscores.
First find the index of _, and then find the next position of _. Then get the substring between them.
var data = "7_28_li";
var idx = data.indexOf("_");
console.log(data.substring(idx + 1, data.indexOf("_", idx + 1)));
# 28
You can understand that better, like this
var data = "7_28_li";
var first = data.indexOf("_");
var next = data.indexOf("_", first + 1);
console.log(data.substring(first + 1, next));
# 28
Note: The second argument to indexOf is to specify where to start looking from.
Probably the easiest way to do it is to call split on your string, with your delimiter ("_" in this case) as the argument. It'll return an array with 7, 28, and li as elements, so you can select the middle one.
"7_28_li".split("_")[1]
This will work if it'll always be 3 elements. If it's more, divide the length property by 2 and floor it to get the right element.
var splitstring = "7_28_li".split("_")
console.log(splitstring[Math.floor(splitstring.length/2)]);
I'm not sure how you want to handle even length strings, but all you have to do is set up an if statement and then do whatever you want.
If you know there would be 2 underscore, you can use this
var str = "7_28_li";
var res = str.substring(str.indexOf("_") +1, str.lastIndexOf("_"));
If you want to find the string between first 2 underscores
var str = "7_28_li";
var firstIndex = str.indexOf("_");
var secondIndex = str.indexOf("_", firstIndex+1);
var res = str.substring(firstIndex+1, secondIndex);

Javascript split only once and ignore the rest

I am parsing some key value pairs that are separated by colons. The problem I am having is that in the value section there are colons that I want to ignore but the split function is picking them up anyway.
sample:
Name: my name
description: this string is not escaped: i hate these colons
date: a date
On the individual lines I tried this line.split(/:/, 1) but it only matched the value part of the data. Next I tried line.split(/:/, 2) but that gave me ['description', 'this string is not escaped'] and I need the whole string.
Thanks for the help!
a = line.split(/:/);
key = a.shift();
val = a.join(':');
Use the greedy operator (?) to only split the first instance.
line.split(/: (.+)?/, 2);
If you prefer an alternative to regexp consider this:
var split = line.split(':');
var key = split[0];
var val = split.slice(1).join(":");
Reference: split, slice, join.
Slightly more elegant:
a = line.match(/(.*?):(.*)/);
key = a[1];
val = a[2];
May be this approach will be the best for such purpose:
var a = line.match(/([^:\s]+)\s*:\s*(.*)/);
var key = a[1];
var val = a[2];
So, you can use tabulations in your config/data files of such structure and also not worry about spaces before or after your name-value delimiter ':'.
Or you can use primitive and fast string functions indexOf and substr to reach your goal in, I think, the fastest way (by CPU and RAM)
for ( ... line ... ) {
var delimPos = line.indexOf(':');
if (delimPos <= 0) {
continue; // Something wrong with this "line"
}
var key = line.substr(0, delimPos).trim();
var val = line.substr(delimPos + 1).trim();
// Do all you need with this key: val
}
Split string in two at first occurrence
To split a string with multiple i.e. columns : only at the first column occurrence
use Positive Lookbehind (?<=)
const a = "Description: this: is: nice";
const b = "Name: My Name";
console.log(a.split(/(?<=^[^:]*):/)); // ["Description", " this: is: nice"]
console.log(b.split(/(?<=^[^:]*):/)); // ["Name", " My Name"]
it basically consumes from Start of string ^ everything that is not a column [^:] zero or more times *. Once the positive lookbehind is done, finally matches the column :.
If you additionally want to remove one or more whitespaces following the column,
use /(?<=^[^:]*): */
Explanation on Regex101.com
function splitOnce(str, sep) {
const idx = str.indexOf(sep);
return [str.slice(0, idx), str.slice(idx+1)];
}
splitOnce("description: this string is not escaped: i hate these colons", ":")

Categories

Resources