If i have a string say, 1234 Newyork Street, America and i want to extract the first LETTER from the string.
I understand how to use
string.charAt(0);
But this extracts for example '1' from the example above. How would i modify the code so if i enter
string.charAt(0);
I extract the first LETTER which is 'N'.
string.replace(/[^a-zA-Z]/g, '').charAt(0);
This will remove anything that is not a letter, then return the first letter.
Use search to get the index of the first letter, then use charAt:
var s = "1234 Newyork Street, America";
s.charAt(s.search(/[a-zA-Z]/));
Both of these will work :
string.replace(/^[1-9\s]+/g,"")[0]
or
replace(/^[1-9\s]+/g,"").charAt(0)
You can use regular expression capturing to find the first letter:
var s = "1234 Newyork Street, America",
result = s.match(/([a-zA-Z]).*/),
firstLetter;
if(result) {
firstLetter = result[1];
}
Related
I have:
var text = 'LTE CSSR (East xr) (301-LT_King_St_PC)'
and I want to split from (East xr) (301-LT_King_St_PC) only as follow :
var result = text.split('(')
result = (East xr) (301-LT_King_St_PC)
You can use a regular expression with the match function to get this done. Depending on how you want the result try one of the following:
var text = 'LTE CSSR (East xr) (301-LT_King_St_PC)'
console.log('one string:', text.match(/\(.*\)/)[0])
console.log('array of strings:', text.match(/\([^\)]*\)/g))
The first does what you seem to be asking for - a single output of everything between the first ( and the second ). It does this by searching for /\(.*\)/ which is a regex that says "everything in between the parentheses".
The second match splits it into all parenthesised strings using /\([^\)]*\)/g which is a regex that says "each parenthesised string" but the g at the end says "all of those" so an array of each is given.
You can do it using substring() and indexOf() :
var text = 'LTE CSSR (East xr) (301-LT_King_St_PC)';
var result = text.substring(text.indexOf('('));
console.log(result);
You're quite close with your current method. One way you could try this is to use multiple characters within your split
var result = text.split(") (")
# Output -> result = ["(East xr", "301-LT_King_St_PC)"]
From here, some string manipulation could get rid of the brackets.
Alternatively you can also use String.match and join its result:
const text = 'LTE CSSR (East xr) (301-LT_King_St_PC)';
const cleaned = text.match(/\(.+[^\)]\)/).join(` `);
console.log(cleaned);
I need to get intials only 2 characters after spaces, here is the sample
const string = "John Peter Don";
const result = string.match(/\b(\w)/g).join('');
console.log(result)// JPD->> i want only JP
One regex approach would be to capture all leading capital letters using match(). Then, slice off the first two elements and join together to form a string output.
var string = "John Peter Don";
var initials = string.match(/\b[A-Z]/g).slice(0, 2).join("");
console.log(initials);
Implementing what Wiktor Stribiżew suggested in the comments
const str = "John Peter Don";
let array = str.split(" ");
console.log(array[0][0], array[1][0]);
console.log("In one string: ", array[0][0] + array[1][0]);
I have a string like
var string = "#developers must split #hashtags";
I want to split it when a word starts with # symbol
I tried these two examples
var example1 = string.split(/(?=#)/g);
//result is ["#developers must split ", "#hashtags"]
var example2 = string.split(/(?:^|[ ])#([a-zA-Z]+)/g);
// result is ["", "developers", "must split", "hashtags", ""]
Result must looks like this
var description = ["#developers", "must split", "#hashtags"]
JSFiddle example
I have a solution but it is a bit long, I want it short with regex. thank you,
When you split, the captured groups are included in the split results array. So you can capture the #word delimiter and omit the space before and after the delimiter with an expression like \s*(#\S+)\s*. Omit empty strings by filter-ing on an expression that tests the truthiness of each string (e.g.: x => x).
let result = "#developers must split #hashtags".split(/\s*(#\S+)\s*/g).filter(x => x);
console.log(result);
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))
I am trying to get this result: 'Summer-is-here'. Why does the code below generate extra spaces? (Current result: '-Summer--Is- -Here-').
function spinalCase(str) {
var newA = str.split(/([A-Z][a-z]*)/).join("-");
return newA;
}
spinalCase("SummerIs Here");
You are using a variety of split where the regexp contains a capturing group (inside parentheses), which has a specific meaning, namely to include all the splitting strings in the result. So your result becomes:
["", "Summer", "", "Is", " ", "Here", ""]
Joining that with - gives you the result you see. But you can't just remove the unnecessary capture group from the regexp, because then the split would give you
["", "", " ", ""]
because you are splitting on zero-width strings, due to the * in your regexp. So this doesn't really work.
If you want to use split, try splitting on zero-width or space-only matches looking ahead to a uppercase letter:
> "SummerIs Here".split(/\s*(?=[A-Z])/)
^^^^^^^^^ LOOK-AHEAD
< ["Summer", "Is", "Here"]
Now you can join that to get the result you want, but without the lowercase mapping, which you could do with:
"SummerIs Here" .
split(/\s*(?=[A-Z])/) .
map(function(elt, i) { return i ? elt.toLowerCase() : elt; }) .
join('-')
which gives you want you want.
Using replace as suggested in another answer is also a perfectly viable solution. In terms of best practices, consider the following code from Ember:
var DECAMELIZE_REGEXP = /([a-z\d])([A-Z])/g;
var DASHERIZE_REGEXP = /[ _]/g;
function decamelize(str) {
return str.replace(DECAMELIZE_REGEXP, '$1_$2').toLowerCase();
}
function dasherize(str) {
return decamelize(str).replace(DASHERIZE_REGEXP, '-');
}
First, decamelize puts an underscore _ in between two-character sequences of lower-case letter (or digit) and upper-case letter. Then, dasherize replaces the underscore with a dash. This works perfectly except that it lower-cases the first word in the string. You can sort of combine decamelize and dasherize here with
var SPINALIZE_REGEXP = /([a-z\d])\s*([A-Z])/g;
function spinalCase(str) {
return str.replace(SPINALIZE_REGEXP, '$1-$2').toLowerCase();
}
You want to separate capitalized words, but you are trying to split the string on capitalized words that's why you get those empty strings and spaces.
I think you are looking for this :
var newA = str.match(/[A-Z][a-z]*/g).join("-");
([A-Z][a-z]*) *(?!$|[a-z])
You can simply do a replace by $1-.See demo.
https://regex101.com/r/nL7aZ2/1
var re = /([A-Z][a-z]*) *(?!$|[a-z])/g;
var str = 'SummerIs Here';
var subst = '$1-';
var result = str.replace(re, subst);
var newA = str.split(/ |(?=[A-Z])/).join("-");
You can change the regex like:
/ |(?=[A-Z])/ or /\s*(?=[A-Z])/
Result:
Summer-Is-Here