indexOf in Javascript not working how it should [duplicate] - javascript

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 8 years ago.
I want to get the page number out if these possible strings:
$scope.projects.next can equal...
string 1) /api/project/?currentuser=false&page=2
string 2)
/api/project/?page=2
I have tried this:
$scope.projects.next.split('=')[1].indexOf("page")
However, this only works on string 2. How can I change this to make sure it finds the page number no matter what position or future arguments that could be added?
I have also tried:
$scope.projects.next.indexOf("page")
but this gives 52 no idea why.

You can use regex:
/page=([0-9]+)/.exec($scope.projects.next)[1]
That uses a regular expression with a capture group (the bit in ()) for the page number, and captures one or more digits after page=. The result is an array, where the first element is the whole match, and the second is the capture group (that's why we have [1] at the end).

please see here: http://jsbin.com/gizalo/1/edit
function to get parametr from string
function getParameterByName(name, string) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(string);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Controller
app.controller('firstCtrl', function($scope){
var stringa="/api/project/?currentuser=false&page=2";
var stringb="/api/project/?page=2";
$scope.a = getParameterByName('page', stringa);
$scope.b = getParameterByName('page', stringb);
});

The problem is that in the first url there are two = signs so your index would be out by 1 on the first url
$scope.projects.next.split('page=')[1]

This has absolutely nothing to do with AngularJS. But it's also simple, so why not answer. Splitting on a character splits on EVERY instance of that character. Your top string is going to end up being ['/api/project/?currentuser', 'false&page', '2'], so getting the position of [1]('page') isn't useful. Split it on ? instead.

var start = $scope.projects.next.indexOf("page=");
var end = $scope.projects.next.indexOf("&");
var page;
if(end == -1) {
page = $scope.projects.next.substring(start+5);
} else {
page = $scope.projects.next.substring(start+5, end);
}
This would also work for ?page=17&test=2

Related

Finding multiple groups in one string

Figure the following string, it's a list of html a separated by commas. How to get a list of {href,title} that are between 'start' and 'end'?
not thisstartfoo, barendnot this
The following regex give only the last iteration of a.
/start((?:<a href="(?<href>.*?)" title="(?<title>.*?)">.*?<\/a>(?:, )?)+)end/g
How to have all the list?
This should give you what you need.
https://regex101.com/r/isYIeR/1
/(?:start)*(?:<a href=(?<href>.*?)\s+title=(?<title>.*?)>.*?<\/a>)+(?:,|end)
UPDATE
This does not meet the requirement.
The Returned Value for a Given Group is the Last One Captured
I do not think this can be done in one regex match. Here is a javascript solution with 2 regex matches to get a list of {href, title}
var sample='startfoo, bar,barendstart<img> something end\n' +
'beginfoo, bar,barend\n'+
'startfoo again, bar again,bar2 againend';
var reg = /start((?:\s*<a href=.*?\s+title=.*?>.*?<\/a>,?)+)end/gi;
var regex2 = /href=(?<href>.*?)\s+title=(?<title>.*?)>/gi;
var step1, step2 ;
var hrefList = [];
while( (step1 = reg.exec(sample)) !== null) {
while((step2 = regex2.exec(step1[1])) !== null) {
hrefList.push({href:step2.groups["href"], title:step2.groups["title"]});
}
}
console.log(hrefList);
If the format is constant - ie only href and title for each tag, you can use this regex to find a string which is not "", and has " and a space or < after it using lookahead (regex101):
const str = 'startfoo, barend';
const result = str.match(/[^"]+(?="[\s>])/gi);
console.log(result);
This regex:
<.*?>
removes all html tags
so for example
<h1>1. This is a title </h1><ul><a href='www.google.com'>2. Click here </a></ul>
After using regex you will get:
1. This is a title 2. Click here
Not sure if this answers your question though.

Replace nth occurence of number in string with javascript [duplicate]

This question already has answers here:
Find and replace nth occurrence of [bracketed] expression in string
(4 answers)
Closed 5 years ago.
This question been asked before, but I did not succeed in solving the problem.
I have a string that contains numbers, e.g.
var stringWithNumbers = "bla_3_bla_14_bla_5";
I want to replace the nth occurence of a number (e.g. the 2nd) with javascript. I did not get farer than
var regex = new RegExp("([0-9]+)");
var replacement = "xy";
var changedString = stringWithNumbers.replace(regex, replacement);
This only changes the first number.
It was suggested to use back references like $1, but this did not help me.
The result should, for example, be
"bla_3_bla_xy_bla_5" //changed 2nd occurence
You may define a regex that matches all occurrences and pass a callback method as the second argument to the replace method and add some custom logic there:
var mystr = 'bla_3_bla_14_bla_5';
function replaceOccurrence(string, regex, n, replace) {
var i = 0;
return string.replace(regex, function(match) {
i+=1;
if(i===n) return replace;
return match;
});
}
console.log(
replaceOccurrence(mystr, /\d+/g, 2, 'NUM')
)
Here, replaceOccurrence(mystr, /\d+/g, 2, 'NUM') takes mystr, searches for all digit sequences with /\d+/g and when it comes to the second occurrence, it replaces with a NUM substring.
var stringWithNumbers = "bla_3_bla_14_bla_5";
var n = 1;
var changedString = stringWithNumbers.replace(/[0-9]+/g,v => n++ == 2 ? "xy" : v);
console.log(changedString);

Regex match cookie value and remove hyphens

I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens. I would like to replace the hyphens with a space and set to a variable. Javascript or jQuery.
As an example, the larger string has a name and value like this within it:
facility=34222%7CConner-Department-Store;
(notice the leading "C")
So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex. Then break it down to "Conner Department Store"
var cookie = document.cookie;
var facilityValue = cookie.match( REGEX ); ??
var test = "store=874635%7Csomethingelse;facility=34222%7CConner-Department-Store;store=874635%7Csomethingelse;";
var test2 = test.replace(/^(.*)facility=([^;]+)(.*)$/, function(matchedString, match1, match2, match3){
return decodeURIComponent(match2);
});
console.log( test2 );
console.log( test2.split('|')[1].replace(/[-]/g, ' ') );
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.
This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Demo:
var str = "facility=34222%7CConner-Department-Store;";
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Explanation:
Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.
Replace any - occurence in the matched words.
Then just join these matches array with white space.
Ok,
first, you should decode this string as follows:
var str = "facility=34222%7CConner-Department-Store;"
var decoded = decodeURIComponent(str);
// decoded = "facility=34222|Conner-Department-Store;"
Then you have multiple possibilities to split up this string.
The easiest way is to use substring()
var solution1 = decoded.substring(decoded.indexOf('|') + 1, decoded.length)
// solution1 = "Conner-Department-Store;"
solution1 = solution1.replace('-', ' ');
// solution1 = "Conner Department Store;"
As you can see, substring(arg1, arg2) returns the string, starting at index arg1 and ending at index arg2. See Full Documentation here
If you want to cut the last ; just set decoded.length - 1 as arg2 in the snippet above.
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1)
//returns "Conner-Department-Store"
or all above in just one line:
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1).replace('-', ' ')
If you want still to use a regular Expression to retrieve (perhaps more) data out of the string, you could use something similar to this snippet:
var solution2 = "";
var regEx= /([A-Za-z]*)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/;
if (regEx.test(decoded)) {
solution2 = decoded.match(regEx);
/* returns
[0:"facility=34222|Conner-Department-Store",
1:"facility",
2:"34222",
3:"Conner-Department-Store",
index:0,
input:"facility=34222|Conner-Department-Store;"
length:4] */
solution2 = solution2[3].replace('-', ' ');
// "Conner Department Store"
}
I have applied some rules for the regex to work, feel free to modify them according your needs.
facility can be any Word built with alphabetical characters lower and uppercase (no other chars) at any length
= needs to be the char =
34222 can be any number but no other characters
| needs to be the char |
Conner-Department-Store can be any characters except one of the following (reserved delimiters): :/?#[]#;,'
Hope this helps :)
edit: to find only the part
facility=34222%7CConner-Department-Store; just modify the regex to
match facility= instead of ([A-z]*)=:
/(facility)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/
You can use cookies.js, a mini framework from MDN (Mozilla Developer Network).
Simply include the cookies.js file in your application, and write:
docCookies.getItem("Connor Department Store");

javascript regex match correct url, with .com or any other domain at the end [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Check if a Javascript string is an url
I am not very familiar with RegEx so it would be great if you could help me solve this problem.
I need a JS function that will:
Check for the string (textarea input) if it has any url.
If yes - search for the first url found and return array(true,url)
If no - return array(false,"")
The problem I am having is this pattern that validates input.
function _is_url(url) {
var pattern = /(((ht|f)tps?\:\/\/)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5})(:[\d]{1,5})?))\S+/i;
var result = new Array();
var testing = pattern.test(url);
if(testing) {
var newurl = url.match(pattern);
result[0] = true;
result[1] = newurl[0];
console.log(result[1]);
}
else {
result[0] = false;
result[1] = "";
}
return result;
}
With this pattern, testing == true even if the url is http://www.youtube which is not a valid url.
What I need is to check the full url: http://www.youtube.com and any other url.
Remove the \S+ after your expression to exclude www.youtube, and add a word boundary \b. Also {1} after the first letter can be omitted.

Regex for parsing parameters from url

I'm a total noob with regexes and although I was trying hard I cannot create proper regexes to perform the following operation :
take url and check if it has a '?' followed by number with varying amount of digits.
if the match is correct, get the number after the '?' sign
exchange this number with different one.
So let's say we have this url :
http://website.com/avatars/avatar.png?56
we take '56' and change it to '57'.
I have the following regex for searching, I'm not sure if it's proper :
\?[0-9]+
But I have no idea how to take ? away. Should I just throw it away from the string and forget about using regex here ? Then the replace part is the only one left.
Try this:
var url = "http://website.com/avatars/avatar.png?56";
var match = url.match(/\?(\d+)/);
if(match != null) {
url = url.replace(match[1], "new number");
}
Your original regex will work just fine, just add back in the ? you are taking out like so:
var newnum = 57;
url = url.replace(/\?[0-9]+/, '?'+ newnum);
I'm no regex expert but I think you can use a lookaround to ignore the '?'
(?<=?)([0-9]+)
which should give you your number in the first match
VERY dummied-down approach:
$('#parse').click(function(e){
var fromUrl = $('#from-url').val();
var newNum = parseInt($('#new-number').val(), 10);
var urlRE = /(?!\?)(\d+)$/;
if (urlRE.test(fromUrl)){
$('#result').text(fromUrl.replace(urlRE, newNum));
}else{
$('#result').text('Invalid URL');
}
});
DEMO
There are not extravagant check-sums, error-checking, etc. Fromt here, use window.location or a string containing the URL if necessary.
Broken out in to a function (demo):
// Call this to replace the last digits with a new number within a url.
function replaceNumber(url, newNumber){
// regex to find (and replace) the numbers at the end.
var urlRE = /\?\d+$/;
// make sure the url end in a question mark (?) and
// any number of digits
if (urlRE.test(url)){
// replace the ?<number> with ?<newNumber>
return url.replace(urlRE, '?'+newNumber);
}
// invalid URL (per regex) just return same result
return url;
}
alert(replaceNumber('http://website.com/avatars/avatar.png?56', 57));
You could do this without regex.
var newNum = "57";
var url = "http://website.com/avatars/avatar.png?56";
var sUrl = url.split('?');
var rUrl = sUrl[0] + "?" + newNum;
alert(rUrl);
Split the URL at the ?
This returns an array.
Add the first item in the array and the ? and the new number back together.
http://jsfiddle.net/jasongennaro/7dMur/

Categories

Resources