how to retrieve a string between to same charecter - javascript

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

Related

Can't put index value inside brackets using RegEx

There are two strings. I'm trying to put index value inside empty brackets:
var capacity = 'room[price_group_ids][][capacity]';
var group = 'room[price_group_ids][][group][%s][]';
For example, If an index is 1, they should be:
var capacity = 'room[price_group_ids][1][capacity]';
var group = 'room[price_group_ids][1][group][%s][]';
And if the index is 2, they should look like as the following:
var capacity = 'room[price_group_ids][2][capacity]';
var group = 'room[price_group_ids][2][group][%s][]';
What I've tried and it gives unexpected result:
var index = 2;
var capacity = 'room[price_group_ids][][capacity]'.replace(/\[(.+?)\]/g, "[" + index +"]"); // Should become room[price_group_ids][2][capacity]
var group = 'room[price_group_ids][][group][%s][]'.replace(/\[(.+?)\]/g, "[" + index +"]"); // Should become room[price_group_ids][2][group][%s][]
I'm not good at RegEx and looking for an advice on how to resolve that
A simple replace should work here.
This will only replace the first occurrence of [], so you don't have to worry about others. g flag is used to replace globally i-e all the occurrences of the specified value
capacity.replace('[]', `[${index}]`);
var index = 2;
var capacity = 'room[price_group_ids][][capacity]';
var group = 'room[price_group_ids][][group][%s][]';
capacity = capacity.replace('[]', `[${index}]`);
group = group.replace('[]', `[${index}]`);
console.log(capacity)
console.log(group)
Since you want to match first occurrence of [] so don't use g flag. Also no need to match anything else (.+?) , just /\[\]/ is enough.
Another way is to simply replace string [] with [1]
let index = 2
console.log('room[price_group_ids][][capacity]'.replace(/\[\]/, `[${index}]`));
console.log('room[price_group_ids][][group][%s][]'.replace(/\[\]/, `[${index}]`));
The reg exp /\[(.+?)\]/g matches 1-or-more of anything between [] brackets. You want to detect [ and ] right next to each other; simply:
/\[\]/
Also, you want to ditch the g at the end, unless you want the replacement to occur for all occurrences of [] -- the g means global.
But there are non-regex approaches, too, as shown in the other answers.

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.

Regular Expression Split and match

I'm learning how to use regular expressions and am a bit confused by something hopefully some one can clarify, if I use the following string and expression I get the expected results with match but the exact opposite if I use split. Beating my head against the wall I don't understand why?
var a = "212,0,,456,,0,67889";
var patt = /,\d{1,5},/gmi;
pos=a.match(patt);
alert(pos);// returns ,0, ,456, and ,0,
pos=a.split(patt);
alert(pos); //returns 212, and ,67889
Split means, look for a match of the pattern on the string and split that string every time you see a match. Also Remove each match you find.
This link has some good examples:
http://www.tizag.com/javascriptT/javascript-string-split.php
"~ a delimiter is used by the split function as a way of breaking up the string. Every time it sees the delimiter we specified, it will create a new element in an array. The first argument of the split function is the delimiter." (The delimiter is the pattern)
Example one:
<script type="text/javascript">
var myString = "123456789";
var mySplitResult = myString.split("5");
document.write("The first element is " + mySplitResult[0]);
document.write("<br /> The second element is " + mySplitResult[1]);
</script>
Output:
The first element is 1234
The second element is 6789
"Make sure you realize that because we chose the 5 to be our delimiter, it is not in our result. This is because the delimiter is removed from the string and the remaining characters are separated by the chasm of space that the 5 used to occupy."
Example Two:
<script type="text/javascript">
var myString = "zero one two three four";
var mySplitResult = myString.split(" ");
for(i = 0; i < mySplitResult.length; i++){
document.write("<br /> Element " + i + " = " + mySplitResult[i]);
}
</script>
Output:
Element 0 = zero
Element 1 = one
Element 2 = two
Element 3 = three
Element 4 = four
Consecutive splits are ignored, so you are just getting the two strings that don't match the regex.
You can use split or match to achieve the same, but you need different regex. For instance, you can use for match:
\d+
Working demo
Code
var re = /\d+/g;
var str = '212,0,,456,,0,67889';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Or you can use this regex to split:
,+
Working demo

Find in a string a comma followed by a space and then a number

I have a string containing this format
"Item 1, Item 2, Another Item, 2004"
I would like to split the string at the , 2004 and format it to display
"<em>Item 1, Item 2, Another Item</em>, 2004"
So far I have this
var myString = "";
var new_html = [];
var splitstring = this.split(',');
$.each(splitstring, function (idx) {
if (new_html.length == 0) new_html.push('<em>' + splitstring[idx] + '</em>');
else new_html.push(splitstring[idx]);
});
myString+=("<span class='line"+index+"'>"+new_html.join(',') + "<br/></span>");
This isn't going to work but if someone can point me in the right direction that would be great.
Try using this pattern:
/, (?=\d)/
This will match a comma, followed by a space, but only if it is later followed by a digit.
The (?=...) is a lookahead assertion. It ensures that the pattern inside the parentheses appears after the matched substring, but it is not included in the match.
You can simply use this in your split function like this:
var splitstring = this.split(/, (?=\d)/);
...
If you'd like to ensure that it's followed by something that looks like a 4-digit year you could use:
/, (?=\d{4})/
Or
/, (?=(?:19|20)\d\d)/
Depending on your exact needs.
Written multi-line for clarity & explanation inline.
var str = "Item 1, Item 2, Another Item, 2004";
var arr = str.split(','); //splitting by commas
var num = arr.pop(); //popping the last value '2004'
var result = '<em>'+ arr.join(',') + '</em>' + ',' + num; //joining back again
result: "<em>Item 1, Item 2, Another Item</em>, 2004"
if the num is an year, you can check as (num < 2099) && (num > 1990) (just an example) and use the condition to do specific stuff

Javascript split array

I have a JavaScript array which contain the staff's Chinese and English names.
Example:
XXX MA Yo-Yo
Where XXX represents the Chinese name: 馬友友.
I want to split this into two parts by using the 1st space " " as an indicator.
for (i = 0; i < /* ... */)
{
w_temp = arr[i];
w_name = w_temp[1].split(' ', 1);
/* ... */
}
w_name[0] successfully returns 馬友友. But w_name[1] returns undefined, which cannot return MA Yo-Yo.
How can I split it into two parts?
Replace your existing w_name = ... line with something like this:
w_name = w_temp[1].split(' ');
w_name = [w_name[0], w_name.slice(1).join(' ')];
The ,1 you had earlier meant to stop parsing as soon as it came to the first space. This is not what you want; you want the part before the first space as one item and the part after as another. The new code parses all of the elements. After that, it sets it to an array consisting of:
The already-existing first element, and
The parts after the first element re-joined.
You have
split(' ', 1)
The 1 means to return at most one part. You should just ommit that or change it to two if thats what you need.
Because you invoke split method with limit = 1, then w_name has only 1 item.
In addition, yours input string has 2 whitespace, therefore, if you use split without limit parameter, w_name will contains 3 items ('XXX', 'CHAN', and 'Tai-Man').
I think you should use this:
var idx = str.indexOf(' ');
if (idx != -1) {
var cn_name = str.substring(0, idx);
var en_name = str.substring(idx + 1);
}
Try this
for (var i = 0; i < arr.length; i++) {
var w_temp = arr[i];
// assuming w_temp contains an array where the second item
// is the full name string
var parts = w_temp[1].match(/^(.+?) (.+)$/);
var cn_name = parts[1];
var en_name = parts[2];
}

Categories

Resources