I got an array containing strings.
I want to make sure there are no space fillings in end or start of string, in middle is ok.
So I've tried using lodash by doing this:
var answers = req.body.answer.split(/;,/); // req.body.answer = 'nio,9'
answers = _.map(answers, _.trimEnd);
answers = _.map(answers, _.trimStart);
The result is this:
[ 'nio , 9' ] // answer before trim
[ 'nio , 9' ] // answer after trim
The wanted result is:
[ 'nio', '9']
I think the problem in your code is your regular expression you are using, you are trying to split the string where there are ;, and I'm guessing you just want to split by , since your result is an array with only one string inside:
[ 'nio , 9' ]
you should use this regular exp instead:
var answers = req.body.answer.split(/,/);
or without any regular exp just do:
var answers = req.body.answer.split(',');
Related
So I know how to get a substring from 2 characters using index or split method. But I'm stuck in a scenario of lots of string with similar names such as:
"2020-12-09-name_of_this_mission_num1_mission1_fileName_something"
"2020-12-09-name_of_this_mission_num1_mission12_fileName_something"
"2020-12-09-name_of_this_mission_num23_mission1_fileName_something_else"
Like I am stuck on how to extract just the "mission#" part, because sometimes the names can be different, so the length is different, and sometimes the names are the same, same as the fileName. I also thought about using the index of "_", but there are multiple "_" and they might end up in different index if the name is different.
Could anyone give me some hint on this?
If the structure of the strings are always the same - and you want the second instance of 'mision' - then split the full string on the text of 'mission'.
This will yield an array with three portions -
["2020-12-09-name_of_this_", "num1", "1_fileName_something"])
Then get the last item in this portions array and grab the number from the start of the resultant string.
Then you can prefix it with the 'mission' that you removed, push it into an array and you have a array of of missions.
If your initial string does not contain a two instances of 'mission' then you can set it to return the 2nd not 3rd portion as I have doen with 'mission2'.
const missions = [
"2020-12-09-name_of_this_mission_num1_mission1_fileName_something",
"2020-12-09-name_of_this_mission_num1_mission12_fileName_something",
"2020-12-09-name_of_this_mission_num23_mission1_fileName_something_else",
"2020-12-09-name_of_this_mission2_fileName_something_else"
]
let missionsArr = [];
missions.forEach(function(mission) {
const missionPortions = mission.split('mission');
let index;
missionPortions.length == 2
? index = 1
: index = 2
missionsArr.push('mission' + parseInt(missionPortions[index]))
})
console.log(missionsArr); //gives ["mission1","mission12", "mission1", "mission2"];
A simple regex match function. Note that 'match' outputs an array, so push match[0]:
const missions = [
"2020-12-09-name_of_this_mission_num1_mission1_fileName_something",
"2020-12-09-name_of_this_mission_num1_mission12_fileName_something",
"2020-12-09-name_of_this_mission_num23_mission1_fileName_something_else"
]
let Arr = [];
missions.forEach(function(mission) {
const missionID = mission.match(/mission\d+/);
Arr.push(missionID[0]);
})
console.log(Arr);
Easiest way to just get the mission##, assuming # is a variable number of digits, is by using regex.
The base regex would be /mission\d+/ which matches the string "mission" followed by at least one number.
Assuming you have your input as:
const missionsTexts = [
"2020-12-09-name_of_this_mission_num1_mission1_fileName_something",
"2020-12-09-name_of_this_mission_num1_mission12_fileName_something",
"2020-12-09-name_of_this_mission_num23_mission1_fileName_something_else"
];
You can transform them into an array of just mission# with the following algorithm:
const missions = missionsTexts.map(missionText => missionText.match(/mission\d+/g)[0]);
Note that this assumes there's only one mission# per missionText. The g modifier is used to make sure the regex doesn't create a match after the first digit it finds.
Working in Javascript attempting to use a regular expression to capture data in a string.
My string appears as this starting with the left bracket
['ABC']['ABC.5']['ABC.5.1']
My goal is to get each piece of the regular expression as a chunk or in array.
I have reviewed and see that the match function might be a good choice.
var myString = "['ABC']['ABC.5']['ABC.5.1']";
myString.match(/\[/g]);
The output I see is only the [ for each element.
I would like the array to be like this for example
myString[0] = ['ABC']
myString[1] = ['ABC.5']
myString[2] = ['ABC.5.1']
What is the correct regular expression and or function to get the above-desired output?
If you just want to separate them, you can use a simple expression or better than that you can split them:
\[\'(.+?)'\]
const regex = /\[\'(.+?)'\]/gm;
const str = `['ABC']['ABC.5']['ABC.5.1']`;
const subst = `['$1']\n`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
DEMO
You can use this regex with split:
\[[^\]]+
Details
\[ - Matches [
[^\]]+ - Matches anything except ] one or more time
\] - Matches ]
let str = `['ABC']['ABC.5']['ABC.5.1']`
let op = str.split(/(\[[^\]]+\])/).filter(Boolean)
console.log(op)
Hi my current string is shown:
082759
078982
074470
066839
062069
062068
062029
062027
059304
059299
056449
056421
052458
050666
100530
078977
072967
072958
072957
066982
062864
062064
056506
052456
24 6 digit numbers in total, notice the new lines between them.
I need this entire string to be broken down into an array such that [082759,078982,etc] is displayed and so that when calling:
console.log(array[0])
will output:
082759
NOTE: The '\n' method does not seem to work and when re-calling it [when within an array], e.g array[0], it outputs all the numbers.
The variable under which this data is derived from comes via:
var currentSku = $(this).attr('data-productsku')
So if this j-query has a specific string type then its probably something to do with this?
Because they have '\n' in-between, use split()
let arr = str.split('\n')
console.log(arr[0]);
If you're adding the digit on a new-line each time, you can use .split() method.
You have to pass the delimiter you want to split by; in your case, you use \n as that's how new-lines are escaped in Javascript. This will create an array of data.
Using the code below you can do like so:
let string = `082759
078982
074470
066839
062069
062068
062029
062027
059304
059299
056449
056421
052458
050666
100530
078977
072967
072958
072957
066982
062864
062064
056506
052456`;
let arr = string.split('\n');
console.log(arr[0]);
Try this code
var test = "082759 078982 074470 066839 062069 062068";
var arr = test.split(" ");
console.log(arr[0]);
console.log(arr[4]);
Tested code!
Note: There should be a space in between each number.
Next line solution is here
var test =
`082759
078982
074470
066839
062069
06206`;
var arr = test.split("\n");
console.log(arr[0]);
console.log(arr[4]);
If splitting using \n doesn't work then it might be that your string is using a different style of line ending. You can try \r or \r\n for instance.
array.split(/\n/)
or
array.split(\n)
Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);
I've a string something like
<dt>Source:</dt>
<dd>
Emergence: Title; 2005, Vol. 9 Issue 30, p120-203, 12p
</dd>
Now I am a regex to fetch different values for it, i.e. : Volume, issue, date etc
so, I fetch entire text using :
var attr = jQuery("dl dt:contains('Source:') ~ dd:eq(0)").text();
And use regex to fetch different values, such as :
To fetch start page I use, following regex:
var regex = new RegExp("p\\d+(?=[-\\s]{1})");
var regexValPS = attr.match(regex);
Return value : p120, expected : 120
Similarly, to fetch Volume info, I use following, regex:
var regexVol = new RegExp("Vol.\\s\\d+");
var regexValVol = attributeVal.match(regexVol);
I get : Vol. 9 , I want : 9
Similarly I am getting issue number with "Issue" text :
var regEx = new RegExp("Issue\\s\\d+");
var regExVal = attributeVal.match(regEx);
I Should get : 30 instead : Issue 30
The problem is I can't use another regex to get the desired value, can't strip/parseInt etc, and the pattern must be able to fetch information in a single regex.
Use grouping (...) and read its match ยป
Demo:
var str = "Emergence: Title; 2005, Vol. 9 Issue 30, p120-203, 12p";
var re = /p(\d+)(?=[\-\s])/;
document.writeln(re.exec(str)[1]); // prints: 120
re = /Vol\.\s(\d+)/;
document.writeln(re.exec(str)[1]); // prints: 9
Test it here.
Toget the desired info using a single regex, you need to take advantage of regex grouping:
var regEx = new RegExp("Issue\\s(\\d+)");
var regExVal = attributeVal.match(regEx)[1];
If you cannot modify the regex, you can maybe parse the resulting number :
var number = "Issue 30".replace(/\D/g, '');
If I understand you correctly, you do not want to do further parsing on the string values returned by the .match() calls, but can accept a different regular expression if it returns the necessary values in one statement.
Your regex needs a capture group () to retrieve the desired numbers, and place them in an array index [] (the first index [0] will hold the entire matched string, and subsequent indices hold the () captured substrings).
Instead of new RegExp() you can use the simpler /pattern/ regex literal in this case, and it is possible to extract the desired value in a single statement for all cases.
var yourString = '<dt>Source:</dt>\
<dd>\
Emergence: Title; 2005, Vol. 9 Issue 30, p120-203, 12p\
</dd>';
// Match the page, captured in index [1]
yourString.match(/p(\d+)(?=[-\s]{1})/)[1];
// "120"
// Match the Vol captured in index [1]
yourString.match(/Vol\.\s(\d+)/)[1];
// "9"
// Match the issue captured in index [1]
yourString.match(/Issue\s(\d+)/)[1];
// "30"
Here it is on jsfiddle
Try this:
var attr = jQuery("dt:contains('Source:') ~ dd:eq(0)").text();
console.log(attr);
console.log(attr.match(/p(\d+)(?=[-\s]{1})/)[1]);
console.log(attr.match(/Vol\.\s(\d+)/)[1]);
console.log(attr.match(/Issue\s(\d+)/)[1]);
For more details: JQUERY REGEX EXAMPLES TO USE WITH .MATCH().