I need to change field dynamic and set format with this code i a formatting my zip code its text come from server end like
123456789
and this jQuery method change this value format
1234-56789
var ZIptext = $("#ZipLabel").text();
var reformat = ZIptext.replace(/(\d{5})/g, function (match) {
return match + "-";
});
$("#ZipLabel").text(reformat.replace(/\-$/, ""))
but know i am facing problem i need to change format of my fax number
3453454354
and it should be like
345-345-4354
So can someone help me
Do it with capturing group regex
var res = '3453454354'.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
document.write(res);
This question is similar to this one here.
You can do this using:
'345345345'.replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
Here's a function to do it generically.
The first argument is the input string, the second is the separator character, and the third is an array of lengths to separate the input with. You can specify a '*' as the last argument as well.
function separate(_input, _separator, _lengths) {
var output = [], i = 0;
for(i=0; i<_lengths.length; i++) {
if(_input.length <= _lengths[i] || _lengths[i] === '*') {
output.push(_input);
break;
}
output.push(_input.substr(0, _lengths[i]));
_input = _input.substr(_lengths[i]);
}
return output.join(_separator);
}
Usage examples:
separate('3453454354', '-', [3, 3, 4]); // returns "345-345-4354"
separate('3453454354', '-', [4,'*']); // returns "3453-454354"
Related
I am trying to extract a string value, but I need a generic code to extract the values.
INPUT 1 : "/rack=1/shelf=1/slot=12/port=200"
INPUT 2 : "/shelf=1/slot=13/port=3"
INPUT 3 : "/shelf=1/slot=142/subslot=2/port=4"
I need the below output:
OUTPUT 1 : "/rack=1/shelf=1/slot=12"
OUTPUT 2 : "/shelf=1/slot=13"
OUTPUT 3 : "/shelf=1/slot=142"
Basically I am trying to extract up to the slot value. I tried indexOf and substr, but those are specific to individual string values. I require a generic code to extract up to slot. Is there a way how I can match the numeric after the slot and perform extraction?
We can try matching on the following regular expression, which captures all content we want to appear in the output:
^(.*\/shelf=\d+\/slot=\d+).*$
Note that this greedily captures all content up to, and including, the /shelf followed by /slot portions of the input path.
var inputs = ["/rack=1/shelf=1/slot=12/port=200", "/shelf=1/slot=13/port=3", "/shelf=1/slot=142/subslot=2/port=4"];
for (var i=0; i < inputs.length; ++i) {
var output = inputs[i].replace(/^(.*\/shelf=\d+\/slot=\d+).*$/, "$1");
console.log(inputs[i] + " => " + output);
}
You could use this function. If "subslot" is always after "slot" then you can remove the "/" in indexOf("/slot")
function exractUptoSlot(str) {
return str.substring(0,str.indexOf("/",str.indexOf("/slot")));
}
If it will always be the last substring, you could use slice:
function removeLastSubStr(str, delimiter) {
const splitStr = str.split(delimiter);
return splitStr
.slice(0, splitStr.length - 1)
.join(delimiter);
}
const str = "/rack=1/shelf=1/slot=12/port=200";
console.log(
removeLastSubStr(str, '/')
)
if you don't know where your substring is, but you know what it is you could filter it out of the split array:
function removeSubStr(str, delimiter, substr) {
const splitStr = str.split(delimiter);
return splitStr
.filter(s => !s.contains(substr))
.join(delimiter);
}
const str = "/rack=1/shelf=1/slot=12/port=200";
console.log(
removeSubStr(str, '/', 'port=200')
)
console.log(
removeSubStr(str, '/', 'port')
)
First off, I am a complete noob. I have just recently started getting good with python and have close to zero knowledge regarding javascript and corvid for wix. I am looking through documentation but I can't figure out how to do the following: When a user fills out a field, let's say a phone number field, how do you validate whether that field has any alphabetical characters or "+" or "-" etc or not?
I am trying to do something like this:
$w.onReady(function () {
$w("#input1").onCustomValidation( (value, reject) => {
if( input1 is anything but an integer ) {
reject("Only Numbers. No '-', '.', '()', '+', or any alphabetical characters");
}
} );
});
I feel like I am close but have no idea. Any help is appreciated
To answer your question:
Includes Function
You would want to use the .includes() function native to javascript which returns a boolean of if it is or isn't included. If you need the string index of each occurrence you would need to use a for loop as shown below.
var string = "+54 2453-2534-242";
for(int i = 0; i < string.length(); i++){
if(string.substr(i,1) === "-"){
console.log(i);
}
}
Includes Function
Replace Function
Below is an example of how to use this function.
If you wish to remove these or one of these characters you can use the .replace() function or the .split() and .join() functions.
const string = "+53 573-2566-242";
const character_1 = "+";
const character_2= "-";
// Includes
console.log(string + ".includes(+):", string.includes(character_1));
console.log(string + ".includes(-):",string.includes(character_2));
// Replace Singular
var new_string = string.replace(character_1,'');
console.log(new_string);
// Replace Multiple
var new_string2 = string.split(character_2).join("");
console.log(new_string2);
Replace Funtion
If you are still stuck, please feel free to comment
Edit
To check if there are any alpha-numeric characters in a string. You can simply use the .replace() function and compare it. As seen below:
var string = "abc546"; // Your Phone Number Input
var string_converted = string.replace(/\D/g,'');
if(string !== string_converted){
console.log("Contains Characters that are not of type NUMBER!");
console.log(`${string} vs ${string_converted}`);
}
In your case, you could use the code below:
$w.onReady(function () {
$w("#input1").onCustomValidation( (value, reject) => {
// Assuing *value* is your input
var converted = value.replace(/\D/g,'');
if(value !== converted){
// Regective Statment Here..
}else{
// All good! (No Alph-numeric Characters)
}
});
});
I am using split function like this :
function getFirstPart(str) {
return str.split('/')[0];
}
function getSecondPart(str) {
return str.split('/')[1];
}
For first part it is working as expected, but for second part i want everything behind first /.
For example in /stub/787878/hello, I want stub as first part and /787878/hello as second part.
How to make pattern for such condition.
Instead of trying to use split, find the slash, and take the string to the left and right of it:
function divideAtSlash(str) {
const index = str.indexOf('/', 1);
return [str.slice(0, index), str.slice(index)];
}
The second argument (1) to indexOf tells it to start matching at the second character, because in this case we want to skip over the leading slash.
The first element of the returned tuple will be /stub, not stub. If you want the latter, then
return [str.slice(1, index), str.slice(index)];
This is what you are looking for:
const str = '/stub/787878/hello/911';
const [, firstPart, ...rest] = str.split('/');
const secondPart = '/' + rest.join('/')
console.log('first part: ', firstPart);
console.log('second part: ', secondPart);
i guess getSecondPart() is returning 787878 in your example.
you need to check how many parts you have in your arrayy after splitting the string and then return every part except the first.
function getSecondPart(str) {
var astr = str.split('/');
str = "";
for(var i = 0; i < astr.length; i++) {
str += "/" + astr[i];
}
return(str);
}
CODE IS NOT TESTED, I just want to give you an idea.
I need to write a function to perform an action only if the URL has a specific string. The issue that I am finding is that the string can come up in multiple instances as part of another string. I need the function to run when the string is ONLY "?page=1". What I am finding is that the function is also being run when the string contains a string like "?page=10" , "?page=11" , "?page=12" , etc... I only need it to be done if the string is "?page=1" - that's it. How do I do that? I've tried a couple of different ways, but it does not work. Any help is appreciated. Here is the latest code that I have used that is close...but no cigar.
var location = window.location.href;
if (location.indexOf("?page=1") > -1){
//Do something
};
?page is a GET parameter. It doesn't necessarily have to be first in the URL string. I suggest you properly decode the GET params and then base your logic on that. Here's how you can do that:
function unparam(qs) {
var params = {},
e,
a = /\+/g,
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); };
while (e = r.exec(qs)) {
params[d(e[1])] = d(e[2]);
}
return params;
}
var urlParams = unparam(window.location.search.substring(1));
if(urlParams['page'] == '1') {
// code here
}
Alternatively, a regex with word boundaries would have worked:
if(/\bpage=1\b/.test(window.location.search)) {
// code here
}
if(location .indexOf("?page=1&") != -1 || (location .indexOf("?page=1") + 7 == i.length) ) {
}
You could look at the character immediately following the string "?page=1" in the url. If it's a digit,you don't have a match otherwise you do. You could trivially do something like this:
var index = location.indexOf("?page=1"); //Returns the index of the string
var number = location.charCodeAt(index+x); //x depends on the search string,here x = 7
//Unicode values for 0-9 is 48-57, check if number lies within this range
Now that you have the Unicode value of the next character, you can easily deduce if the url contains the string you require or not. I hope this points you in the right direction.
I'm trying to write a function that checks a parameter against an array of special HTML entities (like the user entered '&' instead of '&'), and then add a span around those entered entities.
How would I search through the string parameter to find this? Would it be a regex?
This is my code thus far:
function ampersandKiller(input) {
var specialCharacters = ['&', ' ']
if($(specialCharacters).contains('&')) {
alert('hey')
} else {
alert('nay')
}
}
Obviously this doesn't work. Does anyone have any ideas?
So if a string like My name is & was passed, it would render My name is <span>&</span>. If a special character was listed twice -- like 'I really like &&& it would just render the span around each element. The user must also be able to use the plain &.
function htmlEntityChecker(input) {
var characterArray = ['&', ' '];
$.each(characterArray, function(idx, ent) {
if (input.indexOf(ent) != -1) {
var re = new RegExp(ent, "g");
input = input.replace(re, '<span>' + ent + '</span>');
}
});
return input;
}
FIDDLE
You could use this regular expression to find and wrap the entities:
input.replace(/&| /g, '<span>$&</span>')
For any kind of entity, you could use this too:
input.replace(/&(?:[a-z]+|#\d+);/g, '<span>$&</span>');
It matches the "word" entities as well as numeric entities. For example:
'test & & <'.replace(/&(?:[a-z]+|#x?\d+);/gi, '<span>$&</span>');
Output:
test & <span>&</span> <span><</span>
Another option would be to make the browser do a decode for you and check if the length is any different... check this question to see how to unescape the entities. You can then compare the length of the original string with the length of the decoded. Example below:
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
function hasEntities(input) {
if (input.length != htmlDecode(input).length) {
return true;
}
return false;
}
alert(hasEntities('a'))
alert(hasEntities('&'))
The above will show two alerts. First false and then true.