Исправлено решение для SWIFT 3
Чтобы заставить его работать, создайте новый инструмент инструмента командной строки.
Перейдите в «Файл» -> «Создать» -> «Проект», -> «macOS» -> «Инструмент командной строки».
import Foundation
print("Hello, World!")
func solveMefirst(firstNo: Int , secondNo: Int) -> Int {
return firstNo + secondNo
}
func input() -> String {
let keyboard = FileHandle.standardInput
let inputData = keyboard.availableData
return NSString(data: inputData, encoding:String.Encoding.utf8.rawValue) as! String
}
let num1 = readLine()
let num2 = readLine()
var IntNum1 = Int(num1!)
var IntNum2 = Int(num2!)
print("Addition of numbers is : \(solveMefirst(firstNo: IntNum1!, secondNo: IntNum2!))")
И запустите проект, используя CMD + R
Вы можете вызвать функцию getCookie с именем нужного файла cookie, а затем проверить, является ли оно = null.
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin + prefix.length, end));
return decodeURI(dc.substring(begin + prefix.length, end));
}
function doSomething() {
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
// do cookie doesn't exist stuff;
}
else {
// do cookie exists stuff
}
}
regexObject. test (String) является быстрее , чем строка. соответствует (RegExp).
Сайт MDN описывает формат document.cookie и имеет пример regex для захвата файла cookie (document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");
). Исходя из этого, я бы пошел на это:
/^(.*;)?\s*cookie1\s*=/.test(document.cookie);
Вопрос, похоже, требует решения, которое возвращает false, когда cookie установлен, но пуст. В этом случае:
/^(.*;)?\s*cookie1\s*=\s*[^;]/.test(document.cookie);
Тесты
function cookieExists(input) {return /^(.*;)?\s*cookie1\s*=/.test(input);}
function cookieExistsAndNotBlank(input) {return /^(.*;)?\s*cookie1\s*=\s*[^;]/.test(input);}
var testCases = ['cookie1=;cookie1=345534;', 'cookie1=345534;cookie1=;', 'cookie1=345534;', ' cookie1 = 345534; ', 'cookie1=;', 'cookie123=345534;', 'cookie=345534;', ''];
console.table(testCases.map(function(s){return {'Test String': s, 'cookieExists': cookieExists(s), 'cookieExistsAndNotBlank': cookieExistsAndNotBlank(s)}}));
-1
, если установлено cookie_name_whatever
(даже если cookie_name - нет). Версия регекса в другом ответе решает это.
– hajamie
5 January 2017 в 14:25
Если вы просто проверяете наличие файла cookie, почему бы и нет ...
if (isset ($ _ COOKIE ['mycookie'])) {сделайте что-нибудь здесь}
Я создал альтернативную версию, отличную от jQuery:
document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/)
Он проверяет только существование cookie. Более сложная версия также может возвращать значение cookie:
value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]
Поместите ваше имя файла cookie вместо MyCookie
.
Для тех, кто использует Node, я нашел хорошее и простое решение с импортом ES6 и модулем cookie
!
Сначала установите модуль cookie (и сохраните как зависимость):
npm install --save cookie
Затем импортировать и использовать:
import cookie from 'cookie';
let parsed = cookie.parse(document.cookie);
if('cookie1' in parsed)
console.log(parsed.cookie1);
вместо переменной cookie вы бы просто использовали document.cookie.split ...
var cookie = 'cookie1=s; cookie1=; cookie2=test';
var cookies = cookie.split('; ');
cookies.forEach(function(c){
if(c.match(/cookie1=.+/))
console.log(true);
});
Если вы используете jQuery, вы можете использовать плагин jquery.cookie .
Получение значения для определенного файла cookie выполняется следующим образом:
$.cookie('MyCookie'); // Returns the cookie value
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
else{
var oneCookie = dc.indexOf(';', begin);
if(oneCookie == -1){
var end = dc.length;
}else{
var end = oneCookie;
}
return dc.substring(begin, end).replace(prefix,'');
}
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
var fixed = dc.substring(begin, end).replace(prefix,'');
}
// return decodeURI(dc.substring(begin + prefix.length, end));
return fixed;
}
Функция Tried @jac, вызвала некоторые проблемы, вот как я отредактировал его функцию.
ВНИМАНИЕ! выбранный ответ содержит ошибку (ответ Жака).
, если у вас есть несколько файлов cookie (очень вероятно ..), и файл cookie, который вы извлекаете, является первым в списке, он не устанавливает переменная «end» и, следовательно, она вернет всю строку символов, следующих за «cookieName =» в строке document.cookie!
вот пересмотренная версия этой функции:
function getCookie( name ) {
var dc,
prefix,
begin,
end;
dc = document.cookie;
prefix = name + "=";
begin = dc.indexOf("; " + prefix);
end = dc.length; // default to end of the string
// found, and not in first position
if (begin !== -1) {
// exclude the "; "
begin += 2;
} else {
//see if cookie is in first position
begin = dc.indexOf(prefix);
// not found at all or found as a portion of another cookie name
if (begin === -1 || begin !== 0 ) return null;
}
// if we find a ";" somewhere after the prefix position then "end" is that position,
// otherwise it defaults to the end of the string
if (dc.indexOf(";", begin) !== -1) {
end = dc.indexOf(";", begin);
}
return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/"/g, '');
}
вместо этого используйте этот метод:
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
else return null;
}
function doSomething() {
var myCookie = getCookie("MyCookie");
if (myCookie == null) {
// do cookie doesn't exist stuff;
}
else {
// do cookie exists stuff
}
}
unescape
устарел, существует ли какая-либо разница, используяdecodeURIComponent
? – the_nuts 10 August 2016 в 08:27