Javascript SUBSTR - javascript

I have a dynamic string value "radio_3_*".
Like:
1 - radio_3_5
2 - radio_3_8
3 - radio_3_78
4 - radio_3_157
5 - radio_3_475
How can I pick the radio_3 part.

Basic regular expression
var str = "radio_3_5";
console.log(str.match(/^[a-z]+_\d+/i));
And how the reg exp works
/ Start of reg exp
^ Match start of line
[a-z]+ Match A thru Z one or more times
_ Match underscore character
\d+ Match any number one or more times
/ End of Reg Exp
i Ignores case
Or with split
var str = "radio_334_1234";
var parts = str.split("_");
var result = parts[0] + "_" + parts[1];
Or even crazier (would not do)
var str = "radio_334_1234";
var result = str.split("_").slice(0,2).join("_");

You could just take your string and use javascript method match
myString = "radio_334_1234"
myString.match("[A-Za-z]*_[0-9]*")
//output: radio_334
[A-Za-z]* Will take any number of characters in upper or lower case
_ Will take the underscore
[0-9]* Will take any number of characters from 0 to 9

Try this:
var str = 'radio_3_78';
var splitStr = str.split('_');
var result = splitStr[0] + '_' + splitStr[1];
http://jsfiddle.net/7faag7ug/2/

Use split and pop, like below.
"radio_3_475".split("_").pop(); // = 475

Related

RegEx replacing numbers greater than variable in Javascript

I have the string:
"selection1 selection2 selection3 selection4"
I am looking to remove all words that end in a number greater than a variable. For instance:
let str = "selection1 selection2 selection3 selection4";
let x = 2;
let regExp = RegExp(...);
let filtered = str.replace(regExp , ""); // should equal "selection1 selection2"
I came up with the following expression which selects all words that end in numbers greater than 29:
/(selection[3-9][0-9]|[1-9]\d{3}\d*)/gi
The result from this regEx on the string "selection1 selection 40" is [selection40]
I feel that I'm part of the way there.
Given that I'm dealing with single and double digit numbers and am looking to incorporate a variable, what regEx could help me alter this string?
You can use .replace with a callback:
let str = "selection5 selection1 selection2 selection3 selection4";
let x = 2;
let regex = /\s*\b\w+?(\d+)\b/g;
let m;
let repl = str.replace(regex, function($0, $1) {
return ($1 > x ? "" : $0);
}).trim();
console.log( repl );
Regex /\b\w+?(\d+)\b/g matches all the words ending with 1+ digits and captures digits in capture group #1 which we use inside the callback function to compare against variable x.
You can split by whitespace, then capture the group using Regex which gets the only the numeric part and filter it accordingly.
const str = "selection1 selection2 selection3 selection4";
const threshold = 2;
const pattern = /selection(\d+)/
const result = str
.split(' ')
.filter(x => Number(x.match(pattern)[1]) <= threshold)
.join(' ');
console.log(result);

Extract chars enclosed in complex brackets within a string in most efficient way

I have a string in which there are brackets, and in brackets could be another brackets. For example:
var string1 = "1 a (C(b(c+ d)e-fg)) 3# 4df (h j) 5 6 ((k))";
Every open bracket is closed, but not necessarily immediately, meaning, inside a bracket could be another bracket. Chars, digits and other signs like + - # $ % (excluding '!") can be all over the string, grouped or solo.
What I want is to extract every char from brackets (regardless if it is numeral, letter, sign...), and format those chars separated with one blank space, including that if there are chars that go immediately one after another, like "c+" or "e-fg" in example, they would be grouped together. In above example, result would be:
var string2 = "C b c+ d e-fg h j k";
I have this code that does this:
var string1 = '1 a (C(b(c+ d)e-fg)) 3# 4df (h j) 5 6 ((k))';
var opens = new Array();
opens.push(string1.indexOf('('));
string1 = string1.replace('(','!')
var closes = new Array();
var done = false;
while (!done) {
openindex = string1.indexOf('(');
closeindex = string1.indexOf(')');
string1 = string1.replace(')','!').replace('(','!');
if (openindex>closeindex) {
opens.push(openindex);
closes.push(closeindex);
}
if (string1.indexOf(')')==-1) {
closes.push(closeindex);
done = true;
}
}
var string2 = '';
for (var i=0;i<opens.length;i++) string2 = string2 + string1.substring(opens[i],closes[i]);
string2 = string2.replace(/!!/g,' ').replace(/!/g,' ').replace(/ /g,' ');
This works (https://jsfiddle.net/nL2gp80j/1/), but I am looking for more efficient solution. I don't know regex, and maybe this could be acomplished much better and faster with it.
There is a much shorter and better way to achieve desired result without involving regular expressions a lot more:
str = '1 a (C(b(c+ d)e-fg)) 3# 4df (h j) 5 6 ((k))';
array = [], counter = 0;
str.split(/([()])/).filter(Boolean).forEach(function(e, i, a) {
// Increase / decrease counter and push desired values to an array
e == '(' ? counter++ : e == ')' ? counter-- : counter > 0 ? array.push(e) : true;
if (i === a.length - 1)
// Join all values with a whitespace between
console.log(array.join(' '));
});
Use a regex to extract the letters with grouping. Use String.prototype.match() method with a regular expression as an argument for this:
var str = "1 2 (a(b(c d)efg)) 3 4 (h j) 5 6 ((k))";
var ex = str.match(/([a-z])+/g); // will give you grouped letters
console.log(ex.join(" ")); // and join it with a space.
Use this regex /[^a-z]*/ig it will replace everything other than char
var string1 = "1 2 (a(b(c d)efg)) 3 4 (h j) 5 6 ((k))";
string1 = string1.match(/[a-z]+/ig);
string1=string1.join(" ");
console.log(string1);
[Edited from comment #Jai]
Use this, if ensured that the brackets are in the right adjustment.
var string1 = "1 2 (a(b(c d)efg)) 3 4 (h j) 5 6 ((k))";
string1 = string1.replace(/[\(\)]*/ig,'');
alert(string1);
Note: I edited the replace-string beacause there was a copy-paste error.
I don't see a simple way to do it in only one regex, but this does the job:
var string1 = "1 a (C(b(c+ d)e-fg)) 3# 4df (h j) 5 6 ((k))";
// remove before the first (
string1 = string1.replace(/^[^()]*\(/, '(');
// reome after the last )
string1 = string1.replace(/\)[^()]*$/g, ')');
// remove outside parenthesis
string1 = string1.replace(/\)[^()]+\(/g, ')(');
// while there is at least one (
while (string1.indexOf('(') != -1) {
// remove pair of parenthesis
string1 = string1.replace(/\(([^()]+)\)/g, " $1 ");
}
// remove superfluous spaces
string1 = string1.replace(/ +/g, ' ');
console.log(string1);

Backward capture group concatenated with forward capture group

I think the title says it all. I'm trying to get groups and concatenate them together.
I have this text:
GPX 10.802.123/3843­ 1 -­ IDENTIFIER 48
And I want this output:
IDENTIFIER 10.802.123/3843-48
So I want to explicitly say, I want to capture one group before this word and after, then concatenate both, only using regex. Is this possible?
I can already extract the 48 like this:
var text = GPX 10.802.123/3843­ 1 -­ IDENTIFIER 48
var reg = new RegExp('IDENTIFIER' + '.*?(\\d\\S*)', 'i');
var match = reg.exec(text);
Output:
48
Can it be done?
I'm offering 200 points.
You must precisely define the groups that you want to extract before and after the word. If you define the group before the word as four or more non-whitespace characters, and the group after the word as one or more non-whitespace characters, you can use the following regular expression.
var re = new RegExp('(\\S{4,})\\s+(?:\\S{1,3}\\s+)*?' + word + '.*?(\\S+)', 'i');
var groups = re.exec(text);
if (groups !== null) {
var result = groups[1] + groups[2];
}
Let me break down the regular expression. Note that we have to escape the backslashes because we're writing a regular expression inside a string.
(\\S{4,}) captures a group of four or more non-whitespace characters
\\s+ matches one or more whitespace characters
(?: indicates the start of a non-capturing group
\\S{1,3} matches one to three non-whitespace characters
\\s+ matches one or more whitespace characters
)*? makes the non-capturing group match zero or more times, as few times as possible
word matches whatever was in the variable word when the regular expression was compiled
.*? matches any character zero or more times, as few times as possible
(\\S+) captures one or more non-whitespace characters
the 'i' flag makes this a case-insensitive regular expression
Observe that our use of the ? modifier allows us to capture the nearest groups before and after the word.
You can match the regular expression globally in the text by adding the g flag. The snippet below demonstrates how to extract all matches.
function forward_and_backward(word, text) {
var re = new RegExp('(\\S{4,})\\s+(?:\\S{1,3}\\s+)*?' + word + '.*?(\\S+)', 'ig');
// Find all matches and make an array of results.
var results = [];
while (true) {
var groups = re.exec(text);
if (groups === null) {
return results;
}
var result = groups[1] + groups[2];
results.push(result);
}
}
var sampleText = " GPX 10.802.123/3843- 1 -- IDENTIFIER 48 A BC 444.2345.1.1/99x 28 - - Identifier 580 X Y Z 9.22.16.1043/73+ 0 *** identifier 6800";
results = forward_and_backward('IDENTIFIER', sampleText);
for (var i = 0; i < results.length; ++i) {
document.write('result ' + i + ': "' + results[i] + '"<br><br>');
}
body {
font-family: monospace;
}
You can do:
var text = 'GPX 10.802.123/3843­ 1 -­ IDENTIFIER 48';
var match = /GPX\s+(.+?) \d .*?(IDENTIFIER).*?(\d\S*)/i.exec(text);
var output = match[2] + ' ' + match[1] + '-' + match[3];
//=> "IDENTIFIER 10.802.123/3843­-48"
This would be possible through replace function.
var s = 'GPX 10.802.123/3843­ 1 -­ IDENTIFIER 48'
s.replace(/.*?(\S+)\s+\d+\s*-\s*(IDENTIFIER)\s*(\d+).*/, "$2 $1-$3")
^\s*\S+\s*\b(\d+(?:[./]\d+)+)\b.*?-.*?\b(\S+)\b\s*(\d+)\s*$
You can try this.Replace by $2 $1-$3.See demo.
https://regex101.com/r/sS2dM8/38
var re = /^\s*\S+\s*\b(\d+(?:[.\/]\d+)+)\b.*?-.*?\b(\S+)\b\s*(\d+)\s*$/gm;
var str = 'GPX 10.802.123/3843­ 1 -­ IDENTIFIER 48';
var subst = '$2 $1-$3';
var result = str.replace(re, subst);
You can use split too:
var text = 'GPX 10.802.123/3843­ 1 -­ IDENTIFIER 48';
var parts = text.split(/\s+/);
if (parts[4] == 'IDENTIFIER') {
var result = parts[4] + ' ' + parts[1] + '-' + parts[5];
console.log(result);
}

Replace the last and first integers of a string

I have a string like this : var input = "/first_part/5/another_part/3/last_part"
I want to replace the last occurence of integers (3 in my string), then the first occurence (5).
I tried this: input .replace(/\d+/, 3); which replace all occurences. But how to only target the last / first one.
Thanks in advance.
This will replace the first and last single digit in the input string with 3
input.replace(/^(.*?)\d(.*)\d(.*)$/, "$13$23$3");
Here's a reFiddle link that demos this: http://refiddle.com/1am9
More readable:
var replacement = '3';
input.replace(/^(.*?)\d(.*)\d(.*)$/, "$1" + replacement + "$2" + replacement + "$3");
or input.replace(/^(.*?)\d(.*)\d(.*)$/, ["$1", "$2", "$3"].join(replacement)); if that's your thing.
You can use this negative lookahead based regex:
var input = "/first_part/5/another_part/3/last_part";
// replace first number
var r = input.replace(/\d+/, '9').replace(/\d+(?=\D*$)/, '7');
//=> /first_part/9/another_part/7/last_part
Here \d+(?=\D*$) means match 1 or more digits that are followed by all non-digits till end of line.
Here is a pretty rigid approach to your problem, you might want to adapt it to your needs, but it shows one way you can get things done.
// input string
var string = "/first_part/5/another_part/3/last_part";
//match all the parts of the string
var m = string.match(/^(\D+)(\d+)+(\D+)(\d+)(.+)/);
// ["/first_part/5/another_part/3/last_part", "/first_part/", "5", "/another_part/", "3", "/last_part"]
// single out your numbers
var n1 = parseInt(m[2], 10);
var n2 = parseInt(m[4], 10);
// do any operations you want on them
n1 *= 2;
n2 *= 2;
// put the string back together
var output = m[1] + n1 + m[3] + n2 + m[5];
// /first_part/10/another_part/6/last_part

How do i get numbers from this string?

i have this string:
var s = 'http://xxxxxxx.xxx/abcd123456789?abc=1';
how do i get digits 123456789 (between "d" and "?") ?
these digits may vary. the number of digits may vary as well.
How do i get them?? Regex? Which one?
try
'http://xxxxxxx.xxx/abcd123456789?abc=1'.match(/\d+(?=\?)/)[0];
// ^1 or more digits followed by '?'
Try
var regexp = /\/abcd(\d+)\?/;
var match = regexp.exec(input);
var number = +match[1];
Are the numbers always between "abcd" and "?"?
If so, then you can use substring():
s.substring(s.indexOf('abcd'), s.indexOf('?'))
If not, then you can just loop through character by character and check if it's numeric:
var num = '';
for (var i = 0; i < s.length; i++) {
var char = s.charAt(i);
if (!isNaN(char)) {
num += char;
}
}
Yes, regex is the right answer. You'll have something like this:
var s = 'http://xxxxxxx.xxx/abcd123456789?abc=1';
var re = new RegExp('http\:\/\/[^\/]+\/[^\d]*(\d+)\?');
re.exec(s);
var digits = $1;

Categories

Resources