I want to return true if a given string has only a certain character but any number of occurrences of that character.Examples:
// checking for 's'
'ssssss' -> true
'sss s' -> false
'so' -> false
Check this
<div class="container">
<form action="javascript:;" method="post" class="form-inline" id="form">
<input type="text" id="message" class="input-medium" placeholder="Message" value="Hello, world!" />
<button type="button" class="btn" data-action="insert">Show</button>
</form>
</div>
JavaScript
var onloading = (function () {
$('body').on('click', ':button', function () {
var a = document.getElementById("message").value;
var hasS = new RegExp("^[s\s]+$").test(a);
alert(hasS);
});
}());
Example http://jsfiddle.net/kXLv5/40/
Just check if anything other than space and "s" is there and invert the boolean
var look = "s";
if(!new RegExp("[^\s" + look + "]").test(str)){
// valid
}
or check if they're the only one which are present with the usage of character class and anchors ^ and $
var look = "s";
if(new RegExp("^[\s" + look + "]$").test(str)){
// valid
}
Do it with sssssnake
'sss'.split('s').some(s => s) === true
'sssnake'.split('s').some(s => s) === false
first, convert the string into an array using split,
const letters ='string'.split('')
then, use the Set data structure and pass the array as an argument to the constructer. Set will only have unique values.
const unique = new Set(letters)
this unique will have only the unique characters, so, when you pass sss then this will have only a single s.
finally, if the unique array contains only one element, then we can say this string only contains the same letter.
if (unique.size === 1) { // the string contains only the same letters
Your function should look like this,
function isIdentile(string) {
const letters = string.split('');
const unique = new Set(letters)
return unique.size === 1 ? true: false;
}
Use a RegEx:
const allOne = str => /^(.)\1*$/.test(str)
console.log(allOne(prompt("input")))
Explanation of the RegEx:
^(.)\1*$ full RegEx
^ start of line
(.) any character, stored in group 1
\1* repeat group 1 zero or more times
$ end of line
Using Set + Array for this, additionally checking the "" empty string edge case:
const hasOnlyGivenCharType = (str, char) => {
const chars = Array.from(new Set(str))
return !chars.some(c => c !== char) && !!chars.length
}
console.log(hasOnlyGivenCharType('ssssss', 's')) // -> true
console.log(hasOnlyGivenCharType('sss s', 's')) // -> false
console.log(hasOnlyGivenCharType('so', 's')) // -> false
console.log(hasOnlyGivenCharType('', 's')) // -> false
Related
I want the replaceFunction to run only one time. For now works correctly only on first time, E-1 return Ε-1 (APPLE) but when user try to edit text field again system detect
Ε-1 and return Ε-1 (APPLE) (APPLE)..
td.onchange = function(e) {
this.value = this.value.replace(/(\E-(\d+))/g, replaceFunction);
function replaceFunction(match) {
// add additional rules here for more cases
if (match === "E-1") return "Ε-1 (APPLE)";
if (match === "E-2") return "Ε-2 (SUMSUNG)";
.
.
.
if(match === "E-99") return "Ε-99 (LG)";
return match;
}
}
How I stop this?
You can use something like this one more condition:
if (match === "E-1" && match !== "Ε-1 (APPLE)") return "Ε-1 (APPLE)";
this can be optimized, if you put the mapping into object:
var map = {
"E-1": "Ε-1 (APPLE)",
...
}
if (map[match] && !map[match] !== match) { return map[match]; }
and for this to work you will need regex that also match the word after in bracket:
var names = ['APPLE', 'SAMSUNG'];
var re = new RegExp('(E-(\\d+))(?! \\((?:' + names.join('|') + ')\\))', 'g');
Yet another solution is to use only array (this will only work if you E-NUM match index in array)
var names = ['APPLE', 'SAMSUNG'];
var re = new RegExp('(E-(\\d+))(?! \\((?:' + names.join('|') + ')\\))', 'g');
// regex explanation, same as yours but \\d is because it's a string
// we create negative look ahead so we check if next text
// after E-1 is not " (" and any of the names.
// we use (?: to group what's inside it's the same as with ()
// but the value will not be captured so there will be
// no param in function for this group
// so this regex will be the same as yours but will not match "E-1 (APPLE)"
// only "E-1"
this.value = this.value.replace(re, replaceFunction);
function replaceFunction(match, eg, num) {
// convert string to number E starts
var i = parseInt(num, 10) - 1;
if (i <= names.length) {
return match + ' (' + names[i] + ')';
}
}
the regex and function can be created outside of the change function, so it don't create new function on each change.
When replacing, also optionally lookahead for a space and parentheses that come after. This way, in the replacer function, you can check to see if what follows is already the value you want (eg, (APPLE)). If it is, then do nothing - otherwise, replace with the new string:
const replacementsE = [
, // nothing for E-0
'APPLE',
'SUMSUNG',
];
td.onchange = function(e) {
td.value = td.value.replace(/E-(\d+)(?= \(([^)]+)\)|)/g, replaceFunction);
function replaceFunction(match, digits, followingString) {
const replacement = replacementsE[digits];
if (!replacement || replacement === followingString) {
return match;
}
return `E-${digits} (${replacement})`;
}
}
<input id="td">
What /E-(\d+)(?= \(([^)]+)\)|)/ does is:
E- - Match E-
(\d+) - Capture digits in a group
(?= \(([^)]+)\)|) Lookahead for either:
\(([^)]+)\) A literal (, followed by non-) characters, followed by ). If this is matched, the non-) characters will be the second capture group
| - OR match the empty string (so that the lookahead works)
The digits will be the first capture group; the digits variable in the callback. The non-) characters will be the second capture group; the followingString variable in the callback.
If you also want to permit the final ) to be deleted, then make the final ) optional, and also make sure the character set does not match spaces (so that the space following APPLE, with no end ), doesn't get matched):
const replacementsE = [
, // nothing for E-0
'APPLE',
'SUMSUNG',
];
td.onchange = function(e) {
td.value = td.value.replace(/E-(\d+)(?= \(([^) ]+)\)?|)/g, replaceFunction);
function replaceFunction(match, digits, followingString) {
const replacement = replacementsE[digits];
if (!replacement || replacement === followingString) {
return match;
}
console.log(followingString)
return `E-${digits} (${replacement})`;
}
}
<input id="td">
If you want to permit any number of characters before the final ) to be deleted, then check if the replacement startsWith the following string:
const replacementsE = [
, // nothing for E-0
'APPLE',
'SUMSUNG',
];
td.onchange = function(e) {
td.value = td.value.replace(/E-(\d+)(?= \(([^) ]+)\)?|)/g, replaceFunction);
function replaceFunction(match, digits, followingString, possibleTrailingParentheses) {
const replacement = replacementsE[digits];
if (!replacement || replacement === followingString || replacement.startsWith(followingString)) {
return match;
}
return `E-${digits} (${replacement})`;
}
}
<input id="td">
I have a page with a textbox where a user is supposed to enter a 24 character (letters and numbers, case insensitive) registration code. I used maxlength to limit the user to entering 24 characters.
The registration codes are typically given as groups of characters separated by dashes, but I would like for the user to enter the codes without the dashes.
How can I write my JavaScript code without jQuery to check that a given string that the user inputs does not contain dashes, or better yet, only contains alphanumeric characters?
To find "hello" in your_string
if (your_string.indexOf('hello') > -1)
{
alert("hello found inside your_string");
}
For the alpha numeric you can use a regular expression:
http://www.regular-expressions.info/javascript.html
Alpha Numeric Regular Expression
With ES6 MDN docs .includes()
"FooBar".includes("oo"); // true
"FooBar".includes("foo"); // false
"FooBar".includes("oo", 2); // false
E: Not suported by IE - instead you can use the Tilde opperator ~ (Bitwise NOT) with .indexOf()
~"FooBar".indexOf("oo"); // -2 -> true
~"FooBar".indexOf("foo"); // 0 -> false
~"FooBar".indexOf("oo", 2); // 0 -> false
Used with a number, the Tilde operator effective does
~N => -(N+1). Use it with double negation !! (Logical NOT) to convert the numbers in bools:
!!~"FooBar".indexOf("oo"); // true
!!~"FooBar".indexOf("foo"); // false
!!~"FooBar".indexOf("oo", 2); // false
If you have the text in variable foo:
if (! /^[a-zA-Z0-9]+$/.test(foo)) {
// Validation failed
}
This will test and make sure the user has entered at least one character, and has entered only alphanumeric characters.
check if string(word/sentence...) contains specific word/character
if ( "write something here".indexOf("write som") > -1 ) { alert( "found it" ); }
ES6 contains inbuilt method (includes) in String's prototype, which can be used to check if string contains another string or not.
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be'));
Following polyfill can be used to add this method in non-supported browsers. (Source)
if (!String.prototype.includes) {
String.prototype.includes = function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
You're all thinking too hard. Just use a simple Regular Expression, it's your best friend.
var string1 = "Hi Stack Overflow. I like to eat pizza."
var string2 = "Damn, I fail."
var regex = /(pizza)/g // Insert whatever phrase or character you want to find
string1.test(regex); // => true
string2.test(regex); // => false
Learn Regex in 5 minutes?
Use a regular expression to accomplish this.
function isAlphanumeric( str ) {
return /^[0-9a-zA-Z]+$/.test(str);
}
If you're searching for character(s) in the start or at the end of the string, you can also use startsWith and endsWith
const country = "pakistan";
country.startsWith('p'); // true
country.endsWith('n'); // true
var inputString = "this is home";
var findme = "home";
if ( inputString.indexOf(findme) > -1 ) {
alert( "found it" );
} else {
alert( "not found" );
}
To test for alphanumeric characters only:
if (/^[0-9A-Za-z]+$/.test(yourString))
{
//there are only alphanumeric characters
}
else
{
//it contains other characters
}
The regex is testing for 1 or more (+) of the set of characters 0-9, A-Z, and a-z, starting with the beginning of input (^) and stopping with the end of input ($).
Kevins answer is correct but it requires a "magic" number as follows:
var containsChar = s.indexOf(somechar) !== -1;
In that case you need to know that -1 stands for not found.
I think that a bit better version would be:
var containsChar = s.indexOf(somechar) >= 0;
Try this:
if ('Hello, World!'.indexOf('orl') !== -1)
alert("The string 'Hello World' contains the substring 'orl'!");
else
alert("The string 'Hello World' does not contain the substring 'orl'!");
Here is an example: http://jsfiddle.net/oliverni/cb8xw/
String's search function is useful too. It searches for a character as well as a sub_string in a given string.
'apple'.search('pl') returns 2
'apple'.search('x') return -1
If you are reading data from the DOM such as a p or h1 tag, for example, you will want to use two native JavaScript functions, it is quiet easy but limited to es6, at least for the solution I am going to provide. I will search all p tags within the DOM, if the text contains a "T" the entire paragraph will be removed. I hope this little example helps someone out!
HTML
<p>Text you need to read one</p>
<p>Text you need to read two</p>
<p>Text you need to read three</p>
JS
let paras = document.querySelectorAll('p');
paras.forEach(p => {
if(p.textContent.includes('T')){
p.remove();
}
});
You can use string.includes(). Example:
var string = "lorem ipsum hello world";
var include = "world";
var a = document.getElementById("a");
if (string.includes(include)) {
alert("found '" + include + "' in your string");
a.innerHTML = "found '" + include + "' in your string";
}
<p id="a"></p>
Working perfectly.This exmple will help alot.
<script>
function check()
{
var val = frm1.uname.value;
//alert(val);
if (val.indexOf("#") > 0)
{
alert ("email");
document.getElementById('isEmail1').value = true;
//alert( document.getElementById('isEmail1').value);
}else {
alert("usernam");
document.getElementById('isEmail1').value = false;
//alert( document.getElementById('isEmail1').value);
}
}
</script>
<body>
<h1>My form </h1>
<form action="v1.0/user/login" method="post" id = "frm1">
<p>
UserName : <input type="text" id = "uname" name="username" />
</p>
<p>
Password : <input type="text" name="password" />
</p>
<p>
<input type="hidden" class="email" id = "isEmail1" name = "isEmail"/>
</p>
<input type="submit" id = "submit" value="Add User" onclick="return check();"/>
</form>
</body>
A sample regex pattern test you can use to find out if the string contains a character '#':
/(#[A-Za-z])\w+/.test(str_text)
Check if string is alphanumeric or alphanumeric + some allowed chars
The fastest alphanumeric method is likely as mentioned at: Best way to alphanumeric check in Javascript as it operates on number ranges directly.
Then, to allow a few other extra chars sanely we can just put them in a Set for fast lookup.
I believe that this implementation will deal with surrogate pairs correctly correctly.
#!/usr/bin/env node
const assert = require('assert');
const char_is_alphanumeric = function(c) {
let code = c.codePointAt(0);
return (
// 0-9
(code > 47 && code < 58) ||
// A-Z
(code > 64 && code < 91) ||
// a-z
(code > 96 && code < 123)
)
}
const is_alphanumeric = function (str) {
for (let c of str) {
if (!char_is_alphanumeric(c)) {
return false;
}
}
return true;
};
// Arbitrarily defined as alphanumeric or '-' or '_'.
const is_almost_alphanumeric = function (str) {
for (let c of str) {
if (
!char_is_alphanumeric(c) &&
!is_almost_alphanumeric.almost_chars.has(c)
) {
return false;
}
}
return true;
};
is_almost_alphanumeric.almost_chars = new Set(['-', '_']);
assert( is_alphanumeric('aB0'));
assert(!is_alphanumeric('aB0_-'));
assert(!is_alphanumeric('aB0_-*'));
assert(!is_alphanumeric('你好'));
assert( is_almost_alphanumeric('aB0'));
assert( is_almost_alphanumeric('aB0_-'));
assert(!is_almost_alphanumeric('aB0_-*'));
assert(!is_almost_alphanumeric('你好'));
GitHub upstream.
Tested in Node.js v10.15.1.
It's worked to me!
Attribute Contains Selector [name*=”value”]
This is the most generous of the jQuery attribute selectors that match against a value. It will select an element if the selector's string appears anywhere within the element's attribute value. Compare this selector with the Attribute Contains Word selector (e.g. [attr~="word"]), which is more appropriate in many cases.
source: Attribute Contains Selector [name*=”value”] => https://api.jquery.com/attribute-contains-selector/
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>attributeContains demo</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">
<script>
$( "input[name*='man']" ).val( "has man in it!" );
</script>
</body>
</html>
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
const array1 = [1, 2, 3];
console.log(array1.includes(2));
// expected output: true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// expected output: true
console.log(pets.includes('at'));
// expected output: false
know more
Demonstration: The include() method finds the “contains” character in whole string, it will return a true.
var string = "This is a tutsmake.com and this tutorial contains javascript include() method examples."
str.includes("contains");
//The output of this
true
If asterisk * is present in the pattern, then it means a sequence of the same character of length 3 unless it is followed by {N} which represents how many characters should appear in the sequence where N will be at least 1. My goal is to determine if the second string exactly matches the pattern of the first string in the input. I'm having trouble building the Regex pattern
*{2}* mmRRR should return TRUE
*{2}* mRRR should return FALSE
https://jsfiddle.net/82smw9zx/
sample code::
pattern1 = /'queryStrSubStr.charAt(0){patternCount}'/;
var patternMatch = new RegExp(pattern1);
if(queryStrSubStr.match(patternMatch)) {
result = true;
} else result = false;
You need to use new RegExp() to construct your regex pattern with variables (rather than attempting to include a variable directly in your regular expression literal).
You are trying to include variables queryStrSubStr.charAt(0) and patternCount in a regular expression literal like: /'queryStrSubStr.charAt(0){patternCount}'/, but JavaScript does not interpret those strings as variables inside the literal.
Following example demonstrates how to construct your regex pattern with variables as well as incorporating the html input from your fiddle so that you can test various patterns. Code comments explain how the code works.
$('.btn').click(() => {
const result = wildcards($('.enter_pattern').val());
console.log(result);
});
const wildcards = (s) => {
if (s.startsWith('*')) { // if input string starts with *
let pattern;
let [count, text] = s.split(' '); // split input string into count and text
count = count.match(/\{\d+\}/); // match count pattern like {n}
if (count) { // if there is a count
pattern = new RegExp(text.charAt(0) + count); // regex: first character + matched count pattern
} else { // if there is no count
pattern = new RegExp(text.charAt(0) + '{3}'); // regex: first character + default pattern {3}
}
return !!s.match(pattern); // return true if text matches pattern or false if not
} else { // if input string does not start with *
return 'No pattern';
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="enter_pattern" />
<button type="submit" class="btn">Click</button>
/*
Example test output:
Input: *{2}* mmRRR
Log: true
Input: *{2}* mRRR
Log: false
Input: * mmmRRR
Log: true
Input: * mmRRR
Log: false
Input: mmRRR
Log: No pattern
*/
First you need to calulate the pattern using a regex:
/\*\{(\d+)\}\*/
It matches a star, a left Square bracket, followed by one or more digits and ending with a right Square bracket and a star.
How to use:
var text = 'mmRRR';
var char = text.charAt(0);
var pattern = '*{2}*';
var counter = /\*\{(\d+)\}\*/.exec(pattern)[1] || '3';
var regex = new RegeExp('^' + char + '\{' + counter + '}$');
var result = text.match(regex);
I'm aware of the CSS attribute text-transform: capitalize but can anyone help me with replicating this using Javascript?
I would like to pass an argument to my function which will return the string with the first letter of each word capitalized.
I've got this far but I'm stuck trying to break my array of strings in to chunks:
function upper(x){
x = x.split(" ");
// this function should return chunks but when called I'm getting undefined
Array.prototype.chunk = function ( n ) {
return [ this.slice( 0, n ) ].concat( this.slice(n).chunk(n) );
};
x = x.chunk;
}
upper("chimpanzees like cigars")
after the chunk I'm guessing I need to again split each chunk in to the first character and the remaining characters, use .toUpperCase() on the first character, join it back up with the remaining and then join up the chunks again in to a string?
Is there a simpler method for doing this?
I came up with a solution for both a single word and also for an array of words. It will also ensure that all other letters are lowercase for good measure. I used the Airbnb style guide as well. I hope this helps!
const mixedArr = ['foo', 'bAr', 'Bas', 'toTESmaGoaTs'];
const word = 'taMpa';
function capitalizeOne(str) {
return str.charAt(0).toUpperCase().concat(str.slice(1).toLowerCase());
}
function capitalizeMany(args) {
return args.map(e => {
return e.charAt(0).toUpperCase().concat(e.slice(1).toLowerCase());
});
};
const cappedSingle = capitalizeOne(word);
const cappedMany = capitalizeMany(mixedArr);
console.log(cappedSingle);
console.log(cappedMany);
The map function is perfect for this.
w[0].toUpperCase() : Use this to capitalize the first letter of each word
w.slice(1): Return the string from the second character on
EDGE Case
If the user doesn't enter a string, the map function will not work and an error will be raised. This can be guarded against by checking if the user actually entered something.
var userInput = prompt("Enter a string");
var capitalizedString = userInput == "" ? "Invalid String" :
userInput.split(/\s+/).map(w => w[0].toUpperCase() + w.slice(1)).join(' ');
console.log(capitalizedString);
You can use the following solution which doesn't use regex.
function capitalize(str=''){
return str.trim().split('')
.map((char,i) => i === 0 ? char.toUpperCase() : char )
.reduce((final,char)=> final += char, '' )
}
capitalize(' hello') // Hello
"abcd efg ijk lmn".replace(/\b(.)/g, (m => m.toUpperCase())) // Abcd Efg Ijk Lmn
You may want to try a regex approach:
function upperCaseFirst(value) {
var regex = /(\b[a-z](?!\s))/g;
return value ? value.replace(regex, function (v) {
return v.toUpperCase();
}) : '';
}
This will grab the first letter of every word on a sentence and capitalize it, but if you only want the first letter of the sentence, you can just remove the g modifier at the end of the regex declaration.
or you could just iterate the string and do the job:
function capitalize(lowerStr){
var result = "";
var isSpacePrevious = false;
for (var i=0; i<lowerStr.length; i++){
if (i== 0 || isSpacePrevious){
result += lowerStr[i].toUpperCase();
isSpacePrevious = false;
continue;
}
if (lowerStr[i] === ' '){
isSpacePrevious = true;
}
result += lowerStr[i];
}
return result;
}
With regex (i assume) or some other method, how can i convert things like:
marker-image or my-example-setting to markerImage or myExampleSetting.
I was thinking about just splitting by - then convert the index of that hypen +1 to uppercase. But it seems pretty dirty and was hoping for some help with regex that could make the code cleaner.
No jQuery...
Try this:
var camelCased = myString.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
The regular expression will match the -i in marker-image and capture only the i. This is then uppercased in the callback function and replaced.
This is one of the great utilities that Lodash offers if you are enlightened and have it included in your project.
var str = 'my-hyphen-string';
str = _.camelCase(str);
// results in 'myHyphenString'
You can get the hypen and the next character and replace it with the uppercased version of the character:
var str="marker-image-test";
str.replace(/-([a-z])/g, function (m, w) {
return w.toUpperCase();
});
Here's my version of camelCase function:
var camelCase = (function () {
var DEFAULT_REGEX = /[-_]+(.)?/g;
function toUpper(match, group1) {
return group1 ? group1.toUpperCase() : '';
}
return function (str, delimiters) {
return str.replace(delimiters ? new RegExp('[' + delimiters + ']+(.)?', 'g') : DEFAULT_REGEX, toUpper);
};
})();
It handles all of the following edge cases:
takes care of both underscores and hyphens by default (configurable with second parameter)
string with unicode characters
string that ends with hyphens or underscore
string that has consecutive hyphens or underscores
Here's a link to live tests: http://jsfiddle.net/avKzf/2/
Here are results from tests:
input: "ab-cd-ef", result: "abCdEf"
input: "ab-cd-ef-", result: "abCdEf"
input: "ab-cd-ef--", result: "abCdEf"
input: "ab-cd--ef--", result: "abCdEf"
input: "--ab-cd--ef--", result: "AbCdEf"
input: "--ab-cd-__-ef--", result: "AbCdEf"
Notice that strings that start with delimiters will result in a uppercase letter at the beginning.
If that is not what you would expect, you can always use lcfirst.
Here's my lcfirst if you need it:
function lcfirst(str) {
return str && str.charAt(0).toLowerCase() + str.substring(1);
}
Use String's replace() method with a regular expression literal and a replacement function.
For example:
'uno-due-tre'.replace(/-./g, (m) => m[1].toUpperCase()) // --> 'unoDueTre'
Explanation:
'uno-due-tre' is the (input) string that you want to convert to camel case.
/-./g (the first argument passed to replace()) is a regular expression literal.
The '-.' (between the slashes) is a pattern. It matches a single '-' character followed by any single character. So for the string 'uno-due-tre', the pattern '-.' matches '-d' and '-t' .
The 'g' (after the closing slash) is a flag. It stands for "global" and tells replace() to perform a global search and replace, ie, to replace all matches, not just the first one.
(m) => m[1].toUpperCase() (the second argument passed to replace()) is the replacement function. It's called once for each match. Each matched substring is replaced by the string this function returns. m (the first argument of this function) represents the matched substring. This function returns the second character of m uppercased. So when m is '-d', this function returns 'D'.
'unoDueTre' is the new (output) string returned by replace(). The input string is left unchanged.
This doesn't scream out for a RegExp to me. Personally I try to avoid regular expressions when simple string and array methods will suffice:
let upFirst = word =>
word[0].toUpperCase() + word.toLowerCase().slice(1)
let camelize = text => {
let words = text.split(/[-_]/g) // ok one simple regexp.
return words[0].toLowerCase() + words.slice(1).map(upFirst)
}
camelize('marker-image') // markerImage
Here is my implementation (just to make hands dirty)
/**
* kebab-case to UpperCamelCase
* #param {String} string
* #return {String}
*/
function toUpperCamelCase(string) {
return string
.toLowerCase()
.split('-')
.map(it => it.charAt(0).toUpperCase() + it.substring(1))
.join('');
}
// Turn the dash separated variable name into camelCase.
str = str.replace(/\b-([a-z])/g, (_, char) => char.toUpperCase());
Here is another option that combines a couple answers here and makes it method on a string:
if (typeof String.prototype.toCamel !== 'function') {
String.prototype.toCamel = function(){
return this.replace(/[-_]([a-z])/g, function (g) { return g[1].toUpperCase(); })
};
}
Used like this:
'quick_brown'.toCamel(); // quickBrown
'quick-brown'.toCamel(); // quickBrown
You can use camelcase from NPM.
npm install --save camelcase
const camelCase = require('camelcase');
camelCase('marker-image'); // => 'markerImage';
camelCase('my-example-setting'); // => 'myExampleSetting';
Another take.
Used when...
var string = "hyphen-delimited-to-camel-case"
or
var string = "snake_case_to_camel_case"
function toCamelCase( string ){
return string.toLowerCase().replace(/(_|-)([a-z])/g, toUpperCase );
}
function toUpperCase( string ){
return string[1].toUpperCase();
}
Output: hyphenDelimitedToCamelCase
is also possible use indexOf with recursion for that task.
input some-foo_sd_dsd-weqe
output someFooSdDsdWeqe
comparison ::: measure execution time for two different scripts:
$ node camelCased.js
someFooSdDsdWeqe
test1: 2.986ms
someFooSdDsdWeqe
test2: 0.231ms
code:
console.time('test1');
function camelCased (str) {
function check(symb){
let idxOf = str.indexOf(symb);
if (idxOf === -1) {
return str;
}
let letter = str[idxOf+1].toUpperCase();
str = str.replace(str.substring(idxOf+1,idxOf+2), '');
str = str.split(symb).join(idxOf !== -1 ? letter : '');
return camelCased(str);
}
return check('_') && check('-');
}
console.log(camelCased ('some-foo_sd_dsd-weqe'));
console.timeEnd('test1');
console.time('test2');
function camelCased (myString){
return myString.replace(/(-|\_)([a-z])/g, function (g) { return g[1].toUpperCase(); });
}
console.log(camelCased ('some-foo_sd_dsd-weqe'));
console.timeEnd('test2');
Just a version with flag, for loop and without Regex:
function camelCase(dash) {
var camel = false;
var str = dash;
var camelString = '';
for(var i = 0; i < str.length; i++){
if(str.charAt(i) === '-'){
camel = true;
} else if(camel) {
camelString += str.charAt(i).toUpperCase();
camel = false;
} else {
camelString += str.charAt(i);
}
}
return camelString;
}
Use this if you allow numbers in your string.
Obviously the parts that begin with a number will not be capitalized, but this might be useful in some situations.
function fromHyphenToCamelCase(str) {
return str.replace(/-([a-z0-9])/g, (g) => g[1].toUpperCase())
}
function fromHyphenToCamelCase(str) {
return str.replace(/-([a-z0-9])/g, (g) => g[1].toUpperCase())
}
const str1 = "category-123";
const str2 = "111-222";
const str3 = "a1a-b2b";
const str4 = "aaa-2bb";
console.log(`${str1} => ${fromHyphenToCamelCase(str1)}`);
console.log(`${str2} => ${fromHyphenToCamelCase(str2)}`);
console.log(`${str3} => ${fromHyphenToCamelCase(str3)}`);
console.log(`${str4} => ${fromHyphenToCamelCase(str4)}`);
You can also use string and array methods; I used trim to avoid any spaces.
const properCamel = (str) =>{
const lowerTrim = str.trim().toLowerCase();
const array = lowerTrim.split('-');
const firstWord = array.shift();
const caps = array.map(word=>{
return word[0].toUpperCase() + word.slice(1);
})
caps.unshift(firstWord)
return caps.join('');
}
This simple solution takes into account these edge cases.
Single word
Single letter
No hyphen
More than 1 hyphen
const toCamelCase = (text) => text.replace(/(.)([^-|$]*)[-]*/g, (_,letter,word) => `${letter.toUpperCase()}${word.toLowerCase()}`)