Quick Problem - Extracting numbers from a string - javascript

I need to extract a single variable number from a string. The string always looks like this:
javascript:change(5);
with the variable being 5.
How can I isolate it? Many thanks in advance.

Here is one way, assuming the number is always surrounded by parentheses:
var str = 'javascript:change(5);';
var lastBit = str.split('(')[1];
var num = lastBit.split(')')[0];

Use regular expressions:-
var test = "javascript:change(5);"
var number = new RegExp("\\d+", "g")
var match = test.match(number);
alert(match);

A simple RegExp can solve this one:
var inputString = 'javascript:change(5);';
var results = /javascript:change\((\d+)\)/.exec(inputString);
if (results)
{
alert(results[1]); // 5
}
Using the javascript:change part in the match as well ensures that if the string isn't in the proper format, you wont get a value from the matches.

var str = 'javascript:change(5);', result = str.match(/\((\d+)\)/);
if ( result ) {
alert( result[1] )
}

Related

regex to find specific strings in javascript

disclaimer - absolutely new to regexes....
I have a string like this:
subject=something||x-access-token=something
For this I need to extract two values. Subject and x-access-token.
As a starting point, I wanted to collect two strings: subject= and x-access-token=. For this here is what I did:
/[a-z,-]+=/g.exec(mystring)
It returns only one element subject=. I expected both of them. Where i am doing wrong?
The g modifier does not affect exec, because exec only returns the first match by specification. What you want is the match method:
mystring.match(/[a-z,-]+=/g)
No regex necessary. Write a tiny parser, it's easy.
function parseValues(str) {
var result = {};
str.split("||").forEach(function (item) {
var parts = item.split("=");
result[ parts[0] /* key */ ] = parts[1]; /* value */
});
return result;
}
usage
var obj = parseValues("subject=something||x-access-token=something-else");
// -> {subject: "something", x-access-token: "something-else"}
var subj = obj.subject;
// -> "something"
var token = obj["x-access-token"];
// -> "something-else"
Additional complications my arise when there is an escaping schema involved that allows you to have || inside a value, or when a value can contain an =.
You will hit these complications with regex approach as well, but with a parser-based approach they will be much easier to solve.
You have to execute exec twice to get 2 extracted strings.
According to MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string.
Usually, people extract all strings matching the pattern one by one with a while loop. Please execute following code in browser console to see how it works.
var regex = /[a-z,-]+=/g;
var string = "subject=something||x-access-token=something";
while(matched = regex.exec(string)) console.log(matched);
You can convert the string into a valid JSON string, then parse it to retrieve an object containing the expected data.
var str = 'subject=something||x-access-token=something';
var obj = JSON.parse('{"' + str.replace(/=/g, '":"').replace(/\|\|/g, '","') + '"}');
console.log(obj);
I don't think you need regexp here, just use the javascript builtin function "split".
var s = "subject=something1||x-access-token=something2";
var r = s.split('||'); // r now is an array: ["subject=something1", "x-access-token=something2"]
var i;
for(i=0; i<r.length; i++){
// for each array's item, split again
r[i] = r[i].split('=');
}
At the end you have a matrix like the following:
y x 0 1
0 subject something1
1 x-access-token something2
And you can access the elements using x and y:
"subject" == r[0][0]
"x-access-token" == r[1][0]
"something2" == r[1][1]
If you really want to do it with a pure regexp:
var input = 'subject=something1||x-access-token=something2'
var m = /subject=(.*)\|\|x-access-token=(.*)/.exec(input)
var subject = m[1]
var xAccessToken = m[2]
console.log(subject);
console.log(xAccessToken);
However, it would probably be cleaner to split it instead:
console.log('subject=something||x-access-token=something'
.split(/\|\|/)
.map(function(a) {
a = a.split(/=/);
return { key: a[0], val: a[1] }
}));

Regex remove repeated characters from a string by javascript

I have found a way to remove repeated characters from a string using regular expressions.
function RemoveDuplicates() {
var str = "aaabbbccc";
var filtered = str.replace(/[^\w\s]|(.)\1/gi, "");
alert(filtered);
}
Output: abc
this is working fine.
But if str = "aaabbbccccabbbbcccccc" then output is abcabc.
Is there any way to get only unique characters or remove all duplicates one?
Please let me know if there is any way.
A lookahead like "this, followed by something and this":
var str = "aaabbbccccabbbbcccccc";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "abc"
Note that this preserves the last occurrence of each character:
var str = "aabbccxccbbaa";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "xcba"
Without regexes, preserving order:
var str = "aabbccxccbbaa";
console.log(str.split("").filter(function(x, n, s) {
return s.indexOf(x) == n
}).join("")); // "abcx"
This is an old question, but in ES6 we can use Sets. The code looks like this:
var test = 'aaabbbcccaabbbcccaaaaaaaasa';
var result = Array.from(new Set(test)).join('');
console.log(result);

how to extract ip address from string variable in javascript

i have written bellow code in javascript
function reg()
{
var a="ec2-54-234-174-228.compute-1.amazonaws.com";
var r = a.match(/\-[0-9]*/g);
alert(r);
}
i got output like -54,-234,-174,-228,-1 but
i need to extract only 54-234-174-228 IP address from variable a.
Try this:
function reg()
{
var a="ec2-54-234-174-228.compute-1.amazonaws.com";
var r = a.match(/\-[0-9-]*/g);
alert(r[0].substring(1,r[0].length));
}
a.match(/\-[0-9-]*/g); will return [-54-234-174-228,-1]. Getting the first element and removing - from the beginning you get what your IP. You can also add this:
alert(r[0].substring(1,r[0].length).replace(/-/g, '.'));
to return it in IP shape: 54.234.174.228
Try this regexp: /[0-9]{1,3}(-[0-9]{1,3}){3}(?=\.)/
It matches a series of 4 numbers between 1 and 3 digits separated by -, which must be followed by a dot.
get the index of first "." then slice
function reg()
{
var a="ec2-54-234-174-228.compute-1.amazonaws.com";
var r = a.indexOf(".");
alert(a.slice(0,r));
}
"ec2-54-234-174-228.compute-1.amazonaws.com".split('.')[0].split('-').slice(1,5).join('.')
In your case you can simply use this pattern:
var r = a.match(/([^a-z][0-9]+\-[0-9]+\-[0-9]+\-[0-9]+)/g);
One more example:
function reg() {
var a="ec2-54-234-174-228.compute-1.amazonaws.com";
var re = /-(\d+)/ig
var arr = [];
while(digit = re.exec(a)) arr.push(digit[1]);
arr = arr.slice(0,4);
alert(arr)
}
you can use this regEx
"(\\d{2}-\\d{3}-\\d{3}-\\d{3})+"

JavaScript insert text after first parenthesis

everyone. I've got a string looks like
var s = "2qf/tqg4/ad(d=d,s(f)d)"
And I've got another string
var n = "abc = /fd/dsf/sdf/a.doc, "
What I want to do is insert n after the first '('
So it will look like
"2qf/tqg4/ad(abc = /fd/dsf/sdf/a.doc, d=d,s(f)d)"
Just use the replace function:
var result = s.replace("(", "("+n);
This barely needs REs.
var t = s.replace(/\(/, '('+n);
This doesn't need REs at all, as String.replace takes strings as well as REs to specify what should be replaced.
var t = s.replace('(', '('+n);

javascript - get two numbers from a string

I have a string like:
text-345-3535
The numbers can change.
How can I get the two numbers from it and store that into two variables?
var str = "text-345-3535"
var arr = str.split(/-/g).slice(1);
Try it out: http://jsfiddle.net/BZgUt/
This will give you an array with the last two number sets.
If you want them in separate variables add this.
var first = arr[0];
var second = arr[1];
Try it out: http://jsfiddle.net/BZgUt/1/
EDIT:
Just for fun, here's another way.
Try it out: http://jsfiddle.net/BZgUt/2/
var str = "text-345-3535",first,second;
str.replace(/(\d+)-(\d+)$/,function(str,p1,p2) {first = p1;second = p2});
var m = "text-345-3535".match(/.*?-(\d+)-(\d+)/);
m[1] will hold "345" and m[2] will have "3535"
If you're not accustomed to regular expressions, #patrick dw's answer is probably better for you, but this should work as well:
var strSource = "text-123-4567";
var rxNumbers = /\b(\d{3})-(\d{4})\b/
var arrMatches = rxNumbers.exec(strSource);
var strFirstCluster, strSecondCluster;
if (arrMatches) {
strFirstCluster = arrMatches[1];
strSecondCluster = arrMatches[2];
}
This will extract the numbers if it is exactly three digits followed by a dash followed by four digits. The expression can be modified in many ways to retrieve exactly the string you are after.
Try this,
var text = "text-123-4567";
if(text.match(/-([0-9]+)-([0-9]+)/)) {
var x = Text.match(/([0-9]+)-([0-9]+)/);
alert(x[0]);
alert(x[1]);
alert(x[2]);
}
Thanks.
Another way to do this (using String tokenizer).
int idx=0; int tokenCount;
String words[]=new String [500];
String message="text-345-3535";
StringTokenizer st=new StringTokenizer(message,"-");
tokenCount=st.countTokens();
System.out.println("Number of tokens = " + tokenCount);
while (st.hasMoreTokens()) // is there stuff to get?
{words[idx]=st.nextToken(); idx++;}
for (idx=0;idx<tokenCount; idx++)
{System.out.println(words[idx]);}
}
output
words[0] =>text
words[1] => 345
words[2] => 3535

Categories

Resources