discard dynamic characters in string with replace() - javascript

for example 21/10/2013.. I want to remove the /2013..
replace('/2013', '') work but the date might be other value like 2014, 2015 and so on

This removes everything from the last / onwards:
var str = "21/10/2013";
var new_str = str.substring(0,str.lastIndexOf('/'));

Try:
'21/10/2013'.replace(/\/\d+$/,''); // 21/10
which removes the last "/" and any digits following to the end of the string.

Related

How to replace numbers with an empty char

i need to replace phone number in string on \n new line.
My string: Jhony Jhons,jhon#gmail.com,380967574366
I tried this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /[0-9]/g;
var rec = str.trim().replace(regex, '\n').split(','); //Jhony Jhons,jhon#gmail.com,
Number replace on \n but after using e-mail extra comma is in the string need to remove it.
Finally my string should look like this:
Jhony Jhons,jhon#gmail.com\n
You can try this:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var regex = /,[0-9]+/g;
str.replace(regex, '\n');
The snippet above may output what you want, i.e. Jhony Jhons,jhon#gmail.com\n
There's a lot of ways to that, and this is so easy, so try this simple answer:-
var str = 'Jhony Jhons,jhon#gmail.com,380967574366';
var splitted = str.split(","); //split them by comma
splitted.pop(); //removes the last element
var rec = splitted.join() + '\n'; //join them
You need a regex to select the complete phone number and also the preceding comma. Your current regex selects each digit and replaces each one with an "\n", resulting in a lot of "\n" in the result. Also the regex does not match the comma.
Use the following regex:
var str = 'Jhony Jhons,jhon#gmail.com,380967574366'
var regex = /,[0-9]+$/;
// it replaces all consecutive digits with the condition at least one digit exists (the "[0-9]+" part)
// placed at the end of the string (the "$" part)
// and also the digits must be preceded by a comma (the "," part in the beginning);
// also no need for global flag (/g) because of the $ symbol (the end of the string) which can be matched only once
var rec = str.trim().replace(regex, '\n'); //the result will be this string: Jhony Jhons,jhon#gmail.com\n
var str = "Jhony Jhons,jhon#gmail.com,380967574366";
var result = str.replace(/,\d+/g,'\\n');
console.log(result)

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");

RegEx to check first two characters must be "1 (numaric)-" in 9 letter word remaing should be alphanumaric

I tried coding in such way that code was not working
var redEx = /^1-[0-9a-zA-Z]{7}/;
document.getElementById("rowidOpty").value.test(redEx)
Example: '1-5S6AW2R': in the string first letter should be numeric and
second character must be "-" and remain alpha-numeric.
It's regexObj.test(string) instead of string.test(regexObj).
See RegExp.prototype.test() for more information.
console.log(/^1-[0-9a-zA-Z]{7}/.test('1-5S6AW2R'))
You have wrong function syntax:
regexp.test([str])
And the right one is:
var regEx = /^1-[0-9a-zA-Z]{7}/;
var string = '1-5S6AW2R';
console.log(regEx.test(string));
pattern = /^[0-9]-(\w+)/g;
console.log('1-5S6AW2R'.match(pattern))
Try this pattern ^[0-9]-(\w+)
Demo Regex
If you want to validate the input matches exactly one numeric, one dash and 7 alphanumerics exactly, use this:
/^[0-9]-[a-zA-Z-0-9]{7}$/;
or if the first can be only the numeral 1:
/^1-[a-zA-Z-0-9]{7}$/;
If you want to search for all occurrences of this pattern in a string that contains a lot of text:
/(^|\s)[0-9]-[a-zA-Z-0-9]{7}(\s|$)/g;
var restrictivePattern = /^[0-9]-[a-zA-Z-0-9]{7}$/;
var loosePattern = /(^|\s)[0-9]-[a-zA-Z-0-9]{7}(\s|$)/g;
var str = '1-A78Z2TE';
var longStr = 'We have 2 different codes 1-AYRJ3F4 and 4-23RJ3F4';
console.log("Validation of string to match pattern: ", str.match(restrictivePattern))
console.log("Multiple matches in string: ", longStr.match(loosePattern))

Replace match last instance of pattern in a string

I want to only show the value after the - as shown below.
$(function(){
var aa = "ABCDEFGHIJKLMNOPQRS-TUVEXYZ";
var bb = aa.substring(aa.indexOf("-") + 1);
$('#one').text(bb);
});
$(function(){
var cc = "ABC-DEFGHIJ-KLMNOPQRS-TUVEXYZ";
var dd = cc.substring(cc.indexOf("-") + 1);
$('#two').text(dd);
});
this outputs
<div id="one">TUVEXYZ</div>
<div id="two">DEFGHIJ-KLMNOPQRS-TUVEXYZ</div>
The first one works as there is only one dash however when there is multiple dashes my code doesn't work as it just looks for the first -. How would I go about looking for the last - only?
eg If my code was working like I want it to I would expect my end result to look like this.
<div id="one">TUVEXYZ</div>
<div id="two">TUVEXYZ</div>
Use lastIndexOf
var dd = cc.substring(cc.lastIndexOf("-") + 1);
Using regex:
var myregexp = /[^-]*$/;
var result = myregexp.exec(subject)[0];
This regex matches any number of non-dash characters, anchored to the end of the string, which effectively matches everything that follows after the last dash (or the entire string if there is no dash).
This might be the regex you are looking for :)
var.replace( /(?:.*)\-(.*?)$/, $1 ); // or "$1", not really shure in JS

how to extract string part and ignore number in jquery?

I have a string like foobar1, foobaz2, barbar23, nobar100 I want only foobar, foobaz, barbar, nobar and ignoring the number part.
If you want to strip out things that are digits, a regex can do that for you:
var s = "foobar1";
s = s.replace(/\d/g, "");
alert(s);
// "foobar"
(\d is the regex class for "digit". We're replacing them with nothing.)
Note that as given, it will remove any digit anywhere in the string.
This can be done in JavaScript:
/^[^\d]+/.exec("foobar1")[0]
This will return all characters from the beginning of string until a number is found.
var str = 'foobar1, foobaz2, barbar23, nobar100';
console.log(str.replace(/\d/g, ''));
Find some more information about regular expressions in javascript...
This should do what you want:
var re = /[0-9]*/g;
var newvalue= oldvalue.replace(re,"");
This replaces al numbers in the entire string. If you only want to remove at the end then use this:
var re = /[0-9]*$/g;
I don't know how to do that in JQuery, but in JavaScript you can just use a regular expression string replace.
var yourString = "foobar1, foobaz2, barbar23, nobar100";
var yourStringMinusDigits = yourString.replace(/\d/g,"");

Categories

Resources