How to remove the alphabet in my case using JQuery? - javascript

I wants to remove alphabet from string. In my string variable it will have the numbers with alphabet
For example
var myString = '1122D'
// I want remove the last alphabet only from the above variable
var myString = '1122Z3'
// I want remove the `Z3` from above string
var myString = '112DD2'
// I want remove the `DD2` from above string
I know how to replace specific character using .replace('',''). But in my case it is different

If the strings are always made up starting with numbers and you want to get the number up until the first alphabetical character, I'd recommend the use of parseInt() since its behaviour is exactly that it parses numeric characters in a string to a number until it encounters the first non-numeric character where it stops parsing.
var myNumber = parseInt(myString);

use this code:
myString.substr(0,myString.search('[a-zA-Z]'));

You may also do like
myString.replace(/[^\d].*/,"");

You can use regex /([\d]+).+$/g as well:
var regex = /([\d]+).+$/g;
console.log(regex.exec("1122D")[1]);
regex.lastIndex = 0;
console.log(regex.exec("1122Z3")[1]);
regex.lastIndex = 0;
console.log(regex.exec("112DD2")[1]);

Best way -
myString.slice(0, myString.indexOf(myString.match(/[a-zA-Z]/)));

Related

Javascript replace on multiple Japanese character

I want to replace this
"】|"
character from string with this"】".
mystring is ="【権利確定月】|1月"
and desired output is
"【権利確定月】1月".
I have tried with array operation and also with this code:
mystring.replace(/】|/g, '】')
but not working.
I only want to this with sequence for"】|".
Because after that string will grow like this
example:
"【権利確定月】1月|other|other|【other】other|other|other".
I have tried many other solution provided on stack overflow but all regex contain single character I want for above sequence character.
You need to escape the | because it has a special meaning within regex. 】| equates to 】 or (an empty string) so the result is that it replaces 】 with itself and inserts 】 between all the other characters in the string.
var mystring ="【権利確定月】|1月"
var myModifiedString = mystring.replace(/】\|/g, '】');
console.log(myModifiedString);
You need to escape the logical OR operator as it is a metacharacter in RegEx.
var x = "【権利確定月】|1月".replace(/】\|/g, '】');
console.log(x);
You can define the strings that need to be replaced in separate variables. Following worked for me.
var x = "】|";
var y = "】";
var word = "【権利確定月】|1月";
word.replace(x, y)
You can split your string by 】| and join by 】. Or (as was answered before me) escape | in regex.
const string = '【権利確】|】|定月】|1月';
let splitAndJoin = string.split('】|').join('】');
let replaceRegex = string.replace(/】\|/g, '】');
console.log(splitAndJoin);
console.log(replaceRegex);

Javascript timestamp formatting with regular expression?

how do i format a string of 2014-09-10 10:07:02 into something like this:
2014,09,10,10,07,02
Thanks!
Nice and simple.
var str = "2014-09-10 10:07:02";
var newstr = str.replace(/[ :-]/g, ',');
console.log(newstr);
Based on the assumption that you want to get rid of everything but the digits, an alternative is to inverse the regex to exclude everything but digits. This is, in effect, a white-listing approach as compared to the previously posted black-listing approach.
var dateTimeString = "2016-11-23 02:00:00";
var regex = /[^0-9]+/g; // Alternatively (credit zerkms): /\D+/g
var reformattedDateTimeString = dateTimeString.replace(regex, ',');
Note the + which has the effect of replacing groups of characters (e.g. two spaces would be replaced by only a single comma).
Also note that if you intend to use the strings as digits (e.g. via parseInt), numbers with a leading zero are interpreted within JavaScript as being base-8.

String manipulation - getting value after the last position of a char

How I can get the value after last char(. ; + _ etc.):
e.g.
string.name+org.com
I want to get "com".
Is there any function in jQuery?
Use lastIndexOf and substr to find the character and get the part of the string after it:
var extension = name.substr(name.lastIndexOf(".") + 1);
Demo: http://jsfiddle.net/Guffa/K3BWn/
A simple and readable approch to get the substring after the last occurrence of a character from a defined set is to split the string with a regular expression containing a character class and then use pop() to get the last element of the resulting array:
The pop() method removes the last element from an array and returns that element.
See a JS demo below:
var s = 'string.name+org.com';
var result = s.split(/[.;+_]/).pop();
console.log(result);
to split at all non-overlapping occurrences of the regex by default.
NOTE: If you need to match ^, ], \ or -, you may escape them and use anywhere inside the character class (e.g. /[\^\-\]\\]/). It is possible to avoid escaping ^ (if you do not put it right after the opening [), - (if it is right after the opening [, right before the closing ], after a valid range, or between a shorthand character class and another symbol): /[-^\]\\]/.
Also, if you need to split with a single char, no regex is necessary:
// Get the substring after the last dot
var result = 'string.name+org.com'.split('.').pop();
console.log(result);
Not jQuery, just JavaScript: lastIndexOf and substring would do it (not since the update indicating multiple characters). As would a regular expression with a capture group containing a character class followed by an end-of-string anchor, e.g. /([^.;+_]+)$/ used with RegExp#exec or String#match.
E.g. (live copy | source):
var match = /([^.;+_]+)$/.exec(theStringToTest),
result = match && match[1];
var s = "string.name+org.com",
lw = s.replace(/^.+[\W]/, '');
console.log(lw) /* com */
this will also work for
string.name+org/com
string.name+org.info
You can use RegExp Object.
Try this code:
"http://stackoverflow.com".replace(/.*\./,"");
I'll throw in a crazy (i.e. no RegExp) one:
var s = 'string.name+org.com';
var a = s.split('.'); //puts all sub-Strings delimited by . into an Array
var result = a[a.length-1]; //gets the last element of that Array
alert(result);​
EDIT: Since the update of the question is demanding mutiple delimiters to work this is probably not the way to go. Too crazy.....
use javascript function like
url.substr(url.length - 3);
maybe this is too late to consider, this codes works fine for me using jquery
var afterDot = value.substr(value.lastIndexOf('_') + 1);
You could just replate '_' to '.'
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);

Regex in javascript complex

string str contains somewhere within it http://www.example.com/ followed by 2 digits and 7 random characters (upper or lower case). One possibility is http://www.example.com/45kaFkeLd or http://www.example.com/64kAleoFr. So the only certain aspect is that it always starts with 2 digits.
I want to retrieve "64kAleoFr".
var url = str.match([regex here]);
The regex you’re looking for is /[0-9]{2}[a-zA-Z]{7}/.
var string = 'http://www.example.com/64kAleoFr',
match = (string.match(/[0-9]{2}[a-zA-Z]{7}/) || [''])[0];
console.log(match); // '64kAleoFr'
Note that on the second line, I use the good old .match() trick to make sure no TypeError is thrown when no match is found. Once this snippet has executed, match will either be the empty string ('') or the value you were after.
you could use
var url = str.match(/\d{2}.{7}$/)[0];
where:
\d{2} //two digits
.{7} //seven characters
$ //end of the string
if you don't know if it will be at the end you could use
var url = str.match(/\/\d{2}.{7}$/)[0].slice(1); //grab the "/" at the begining and slice it out
what about using split ?
alert("http://www.example.com/64kAleoFr".split("/")[3]);
var url = "http://www.example.com/",
re = new RegExp(url.replace(/\./g,"\\.") + "(\\d{2}[A-Za-z]{7})");
str = "This is a string with a url: http://www.example.com/45kaFkeLd in the middle.";
var code = str.match(re);
if (code != null) {
// we have a match
alert(code[1]); // "45kaFkeLd"
}​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
The url needs to be part of the regex if you want to avoid matching other strings of characters elsewhere in the input. The above assumes that the url should be configurable, so it constructs a regex from the url variable (noting that "." has special meaning in a regex so it needs to be escaped). The bit with the two numbers and seven letter is then in parentheses so it can be captured.
Demo: http://jsfiddle.net/nnnnnn/NzELc/
http://www\\.example\\.com/([0-9]{2}\\w{7}) this is your pattern. You'll get your 2 digits and 7 random characters in group 1.
If you notice your example strings, both strings have few digits and a random string after a slash (/) and if the pattern is fixed then i would rather suggest you to split your string with slash and get the last element of the array which was the result of the split function.
Here is how:
var string = "http://www.example.com/64kAleoFr"
ar = string.split("/");
ar[ar.length - 1];
Hope it helps

Is it possible to compare a char to regexp?

I want to check if a single character matches a set of possible other characters so I'm trying to do something like this:
str.charAt(0) == /[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/
since it doesn't work is there a right way to do it?
Use test
/[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/.test(str.charAt(0))
Yes, use:
if(str.charAt(0).match(/[\[\]\.,-\/#!$%\^&\*;:{}=\-_`~()]/))
charAt just returns a one character long string, there is no char type in Javascript, so you can use the regular string functions on it to match against a regex.
Another option, which is viable as long as you are not using ranges:
var chars = "[].,-/#!$%^&*;:{}=-_`~()";
var str = '.abc';
var c = str.charAt(0);
var found = chars.indexOf(c) > 1;
Example: http://jsbin.com/esavam
Another option is keeping the characters in an array (for example, using chars.split('')), and checking if the character is there:
How do I check if an array includes an object in JavaScript?

Categories