RegEx extract all real numbers from a string [duplicate] - javascript

This question already has answers here:
Regex exec only returning first match [duplicate]
(3 answers)
Closed 8 years ago.
This regex in JavaScript is returning only the first real number from a given string, where I expect an array of two, as I am using /g. Where is my mistake?
/[-+]?[0-9]*\.?[0-9]+/g.exec("-8.075090 -35.893450( descr)")
returns:
["-8.075090"]

Try this code:
var input = "-8.075090 -35.893450( descr)";
var ptrn = /[-+]?[0-9]*\.?[0-9]+/g;
var match;
while ((match = ptrn.exec(input)) != null) {
alert(match);
}
Demo
http://jsfiddle.net/kCm4z/
Discussion
The exec method only returns the first match. It must be called repeatedly until it returns null for gettting all matches.
Alternatively, the regex can be written like this:
/[-+]?\d*\.?\d+/g

String.prototype.match gives you all matches:
var r = /[-+]?[0-9]*\.?[0-9]+/g
var s = "-8.075090 -35.893450( descr)"
console.log(s.match(r))
//=> ["-8.075090", "-35.893450"]

Related

Get duplicate characters count in a string [duplicate]

This question already has answers here:
Counting frequency of characters in a string using JavaScript [duplicate]
(21 answers)
Closed 7 years ago.
Can anyone help me to get the count of repeated characters in a given string in javascript.
For example,
"abccdef" -> 1 (Only "c" repeated)
"Indivisibilities" -> 2 ("i" and "s" repeated)
Thank You
You can use like this
function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}
return freq;
};
getFrequency('Indivisibilities');
This is an interesting problem. What we can do is turn the string to lower case using String.toLowerCase, and then split on "", so we get an array of characters.
We will then sort it with Array.sort. After it has been sorted, we will join it using Array.join.
We can then make use of the regex /(.)\1+/g which essentially means match a letter and subsequent letters if it's the same.
When we use String.match with the stated regex, we will get an Array, whose length is the answer. Also used some try...catch to return 0 in case match returns null and results in TypeError.
function howManyRepeated(str){
try{ return str.toLowerCase().split("").sort().join("").match(/(.)\1+/g).length; }
catch(e){ return 0; } // if TypeError
}
console.log(howManyRepeated("Indivisibilities")); // 2

Javascript get the string between two symbols [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
I have the following string and I'm trying to retrieve the string between two symbols
http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_search&wpv-women-clothing[]=coats
I need to retrieve wpv-women-clothing[] or any other string between the last & and the last = in the URL
Should I use regex for this or is there a function in Javascript/jQuery already well suited for this?
Thanks
var str = "http://mytestdomain.com/temp-param-page-2/?wpv_paged_preload_reach=1&wpv_view_count=1&wpv_post_id=720960&wpv_post_search&wpv-women-clothing[]=coats";
var last =str.split('&').pop().split('=')
console.log(last[0]) // wpv-women-clothing[]
jsFiddle example
Split the string on the ampersands (.split('&')), take the last one (.pop()), then split again on the = (.split('=')) and use the first result last[0].
.*&(.*?)=.*
This should do it.
See demo.
http://regex101.com/r/lZ5bT3/1
Group index 1 contains your desired output,
\&([^=]*)(?==[^&=]*$)
DEMO
> var re = /\&([^=]*)(?==[^&=]*$)/g;
undefined
> while ((m = re.exec(str)) != null) {
... console.log(m[1]);
... }
wpv_post_search&wpv-women-clothing[]
Can you try:
var String = "some text";
String = $("<div />").html(String).text();
$("#TheDiv").append(String);

Check if the string ends with a question mark using jquery [duplicate]

This question already has answers here:
How to get the last character of a string?
(15 answers)
Closed 8 years ago.
How can check the entered input is a valid question format using jquery ?
for eg: i have a string "How are you ?" . and i need to identify whether it is a
question or not .Do that all i need is to check whether the string ends with '?' ?. Thanks .
This will do the trick...
if (value.substr(-1) === "?") {
// do what you need here
}
string.substr(x) will start at the character with index x and go to the end of the string. This is normally a positive number so "abcdef".substr(2) returns "cdef". If you use a negative number then it counts from the end of the string backwards. "abcdef".substr(-2) returns "ef".
string.substr(-1) just returns the last character of the string.
If you want a cute endsWith function:
String.prototype.endsWith = function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};
console.log('Is this a question ?'.endsWith('?')); // true
Took the answer here.
You can use \?$ regex to find strings ending with ? mark.
var str = "what is your name?";
var patt = new RegExp("\? $");
if (patt.test(str))
{
// do your stuff
}

How to trim a string to its last four characters? [duplicate]

This question already has answers here:
How to get the last character of a string?
(15 answers)
Closed 8 years ago.
I know there are methods to remove characters from the beginning and from the end of a string in Javascript. What I need is trim a string in such a way that only the last 4 characters remain.
For eg:
ELEPHANT -> HANT
1234567 -> 4567
String.prototype.slice will work
var str = "ELEPHANT";
console.log(str.slice(-4));
//=> HANT
For, numbers, you will have to convert to strings first
var str = (1234567).toString();
console.log(str.slice(-4));
//=> 4567
FYI .slice returns a new string, so if you want to update the value of str, you would have to
str = str.slice(-4);
Use substr method of javascript:
var str="Elephant";
var n=str.substr(-4);
alert(n);
You can use slice to do this
string.slice(start,end)
lets assume you use jQuery + javascript as well.
Lets have a label in the HTML page with id="lblTest".
<script type="text/javascript">
function myFunc() {
val lblTest = $("[id*=lblTest]");
if (lblTest) {
var str = lblTest.text();
// this is your needed functionality
alert(str.substring(str.length-4, str.length));
} else {
alert('does not exist');
}
}
</script>
Edit: so the core part is -
var str = "myString";
var output = str.substring(str.length-4, str.length);

Javascript Regular Expression multiple match [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 6 years ago.
I'm trying to use javascript to do a regular expression on a url (window.location.href) that has query string parameters and cannot figure out how to do it. In my case, there is a query string parameter can repeat itself; for example "quality", so here I'm trying to match "quality=" to get an array with the 4 values (tall, dark, green eyes, handsome):
http://www.acme.com/default.html?id=27&quality=tall&quality=dark&quality=green eyes&quality=handsome
You can use a regex to do this.
var qualityRegex = /(?:^|[&;])quality=([^&;]+)/g,
matches,
qualities = [];
while (matches = qualityRegex.exec(window.location.search)) {
qualities.push(decodeURIComponent(matches[1]));
}
jsFiddle.
The qualities will be in qualities.
A slight variation of #alex 's answer for those who want to be able to match non-predetermined parameter names in the url.
var getUrlValue = function(name, url) {
var valuesRegex = new RegExp('(?:^|[&;?])' + name + '=([^&;?]+)', 'g')
var matches;
var values = [];
while (matches = valuesRegex.exec(url)) {
values.push(decodeURIComponent(matches[1]));
}
return values;
}
var url = 'http://www.somedomain.com?id=12&names=bill&names=bob&names=sally';
// ["bill", "bob", "sally"]
var results = getUrlValue('names', url);
jsFiddle

Categories