How do I enhance slugify to handle Camel Case? - javascript

I'd like to write a JavaScript function to slugify a string, with one more requirement: handle Camel Case. For example, thisIsCamelCase would become this-is-camel-case.
How do I modify a function like this to do so?
EDIT
Added full, answered example.

You just need to add one line of code to what you posted
str = str.replace(/[A-Z]/g, function(s){ return "-" + s; });
This brings the remaining code to be
function string_to_slug(str) {
str = str.replace(/^\s+|\s+$/g, ''); // trim
str = str.replace(/[A-Z]/g, function(s){ return "-" + s; }); // camel case handling
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;",
to = "aaaaeeeeiiiioooouuuunc------";
for (var i=0, l=from.length ; i<l ; i++) {
str = str.replace(from[i], to[i]);
}
str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
return str;
}
Edit :: I also deleted the useless new RegExp logic too.
Edit :: Added 'g' to find all caps, not just the first one.

This will help you!
var strings = 'toDo';
var i=0;
var ch='';
while (i < strings.length){
character = strings.charAt(i);
if (character == character.toUpperCase()) {
//alert ('upper case true' + character);
character = "-" + character.toLowerCase();
}
i++;
ch += character;
}
//to-do
alert(ch);

Try using:
str=str.toLowerCase() before or after the slugification.

Related

How to apply special characters in string?

Suppose we have the following string object:
var str = "Real\bWorl\bd";
considering \b as BackSpace character, I want a mechanism to get
ReaWord
as result, this means BackSpace character some how compiled within the string.
aside from BackSpace, this special character might be Delete.
Thanks in advance....
try this
function replaceBackslash(str)
{
return str.split(/[a-z]\b/).join("")+ str.charAt(str.length -1);
}
replaceBackslash( "Real\bWorld\bddd" );
replaceBackslash( "Real\bWorld" );
function formatStr(str){
if(str.indexOf("\b")!=-1){
return formatStr(str.substring(0, str.indexOf("\b")-1) +
str.substring(str.indexOf("\b")+1, str.length));
}
else return str;
}
var str = "Real\bWor\bld";
alert(formatStr(str));
Check this
function removeBackspaces()
{
var str = "Real\bWorl\bd";
var word = "";
for(var i=0; i < str.length; i++)
{
if(str[i] != '\b')
{
word += str[i]
}
else
{
//var lastIndex = word.lastIndexOf(" ");
word = word.substring(0, word.length-1);
}
}
return word;
}
use following code
unescape(str)

Javascript: Cut string after last specific character

I'm doing some Javascript to cut strings into 140 characters, without breaking words and stuff, but now i want the text so have some sense. so i would like if you find a character (just like ., , :, ;, etc) and if the string is>110 characters and <140 then slice it, so the text has more sense. Here is what i have done:
where texto means text, longitud means length, and arrayDeTextos means ArrayText.
Thank you.
//function to cut strings
function textToCut(texto, longitud){
if(texto.length<longitud) return texto;
else {
var cortado=texto.substring(0,longitud).split(' ');
texto='';
for(key in cortado){
if(key<(cortado.length-1)){
texto+=cortado[key]+' ';
if(texto.length>110 && texto.length<140) {
alert(texto);
}
}
}
}
return texto;
}
function textToCutArray(texto, longitud){
var arrayDeTextos=[];
var i=-1;
do{
i++;
arrayDeTextos.push(textToCut(texto, longitud));
texto=texto.replace(arrayDeTextos[i],'');
}while(arrayDeTextos[i].length!=0)
arrayDeTextos.push(texto);
for(key in arrayDeTextos){
if(arrayDeTextos[key].length==0){
delete arrayDeTextos[key];
}
}
return arrayDeTextos;
}
Break the string into sentences, then check the length of the final string before appending each sentence.
var str = "Test Sentence. Test Sentence";
var arr = str.split(/[.,;:]/) //create an array of sentences delimited by .,;:
var final_str = ''
for (var s in arr) {
if (final_str.length == 0) {
final_str += arr[s];
} else if (final_str.length + s.length < 140) {
final_str += arr[s];
}
}
alert(final_str); // should have as many full sentences as possible less than 140 characters.
I think Martin Konecny's solution doesn't work well because it excludes the delimiter and so removes lots of sense from the text.
This is my solution:
var arrTextChunks = text.split(/([,:\?!.;])/g),
finalText = "",
finalTextLength = 0;
for(var i = 0; i < arrTextChunks.length; i += 2) {
if(finalTextLength + arrTextChunks[i].length + 1 < 140) {
finalText += arrTextChunks[i] + arrTextChunks[i + 1];
finalTextLength += arrTextChunks[i].length;
} else if(finalTextLength > 110) {
break;
}
}
http://jsfiddle.net/Whre/3or7j50q/3/
I'm aware of the fact that the i += 2 part does only make sense for "common" usages of punctuation (a single dot, colon etc.) and nothing like "hi!!!?!?1!1!".
Should be a bit more effective without regex splits.
var truncate = function (str, maxLen, delims) {
str = str.substring(0, maxLen);
return str.substring(0, Math.max.apply(null, delims.map(function (s) {
return str.lastIndexOf(s);
})));
};
Try this regex, you can see how it works here: http://regexper.com/#%5E(%5Cr%5Cn%7C.)%7B1%2C140%7D%5Cb
str.match(/^(\r\n|.){1,140}\b/g).join('')

Replacing the last character in a string javascript

How do we replace last character of a string?
SetCookie('pre_checkbox', "111111111111 11 ")
checkbox_data1 = GetCookie('pre_checkbox');
if(checkbox_data1[checkbox_data1.length-1]==" "){
checkbox_data1[checkbox_data1.length-1]= '1';
console.log(checkbox_data1+"after");
}
out put on console : 111111111111 11 after
Last character was not replaced by '1' dont know why
also tried : checkbox_data1=checkbox_data1.replace(checkbox_data1.charAt(checkbox_data1.length-1), "1");
could some one pls help me out
Simple regex replace should do what you want:
checkbox_data1 = checkbox_data1.replace(/.$/,1);
Generic version:
mystr = mystr.replace(/.$/,"replacement");
Remember that just calling str.replace() doesn't apply the change to str unless you do str = str.replace() - that is, apply the replace() function's return value back to the variable str
use regex...
var checkbox_data1 = '111111111111 11 ';
checkbox_data1.replace(/ $/,'$1');
console.log(checkbox_data1);
This will replace the last space in the string.
You have some space in our string please try it
checkbox_data1=checkbox_data1.replace(checkbox_data1.charAt(checkbox_data1.length-4), "1 ");
then add the space in
console.log(checkbox_data1+" after");
This is also a way, without regexp :)
var string = '111111111111 11 ';
var tempstr = '';
if (string[string.length - 1] === ' ') {
for (i = 0; i < string.length - 1; i += 1) {
tempstr += string[i];
}
tempstr += '1';
}
You can try this,
var checkbox_data1=checkbox_data1.replace(checkbox_data1.slice(-1),"+");
This will replace the last character of Your string with "+".
As Rob said, strings are immutable. Ex:
var str = "abc";
str[0] = "d";
console.log(str); // "abc" not "dbc"
You could do:
var str = "111 ";
str = str.substr(0, str.length-1) + "1"; // this makes a _new_ string

Regular Expression for ignoring a string in javascript

Im building a query to submit to a search, one of the input fields is a filter for "OR". I need to replace whitespace with +OR+..only if the whitespace occurs outside of quoted text. So this is the logic:
"Happy Days"+OR+"Love Boat"
I have working code that will do that here:
var filter2=$('[name=filter2]').val();
var str2 = jQuery.trim(filter2);
var filter2d = str2.replace(/" "/g, "\"+OR+\"");
This only works if the text has quotes..I would like to be able to do this as well:
fonzy+OR+"Happy Days"+OR+"Love Boat"
Any help is appreciated
You can do it like this too.
'"abc def" ghi "klmno pqr"'.match(/"[^"]*"|[^\s]+/g).join("+OR+");
Nailed it:
var input = '"abc def" ghi "klmno pqr" xyz';
input.replace (/("[^"]*"|\w+)(\s+|$)/g,'$1+OR+').slice (0,-4) ===
'"abc def"+OR+ghi+OR+"klmno pqr"+OR+xyz'
This assumes that your quoted strings contain no quote characters.
This should do it...
function replaceWhiteSpace(str)
{
insideAQuote = false;
len = str.length
for (i=0; i < len; i++)
{
if (str.charAt(i) == '"')
{
insideAQuote = !insideAQuote;
}
else if (str.charAt(i) == ' ' && !insideAQuote)
{
str = str.substr(0, i) + "+OR+" + str.substr(i+1);
}
}
alert(str);
}

Replace all spaces in a string with '+' [duplicate]

This question already has answers here:
How do I replace all occurrences of a string in JavaScript?
(78 answers)
Closed 7 years ago.
I have a string that contains multiple spaces. I want to replace these with a plus symbol. I thought I could use
var str = 'a b c';
var replaced = str.replace(' ', '+');
but it only replaces the first occurrence. How can I get it replace all occurrences?
You need the /g (global) option, like this:
var replaced = str.replace(/ /g, '+');
You can give it a try here. Unlike most other languages, JavaScript, by default, only replaces the first occurrence.
Here's an alternative that doesn't require regex:
var str = 'a b c';
var replaced = str.split(' ').join('+');
var str = 'a b c';
var replaced = str.replace(/\s/g, '+');
You can also do it like:
str = str.replace(/\s/g, "+");
Have a look at this fiddle.
Use global search in the string. g flag
str.replace(/\s+/g, '+');
source: replaceAll function
Use a regular expression with the g modifier:
var replaced = str.replace(/ /g, '+');
From Using Regular Expressions with JavaScript and ActionScript:
/g enables "global" matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one.
You need to look for some replaceAll option
str = str.replace(/ /g, "+");
this is a regular expression way of doing a replaceAll.
function ReplaceAll(Source, stringToFind, stringToReplace) {
var temp = Source;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
}
String.prototype.ReplaceAll = function (stringToFind, stringToReplace) {
var temp = this;
var index = temp.indexOf(stringToFind);
while (index != -1) {
temp = temp.replace(stringToFind, stringToReplace);
index = temp.indexOf(stringToFind);
}
return temp;
};
NON BREAKING SPACE ISSUE
In some browsers
(MSIE "as usually" ;-))
replacing space in string ignores the non-breaking space (the 160 char code).
One should always replace like this:
myString.replace(/[ \u00A0]/, myReplaceString)
Very nice detailed explanation:
http://www.adamkoch.com/2009/07/25/white-space-and-character-160/
Do this recursively:
public String replaceSpace(String s){
if (s.length() < 2) {
if(s.equals(" "))
return "+";
else
return s;
}
if (s.charAt(0) == ' ')
return "+" + replaceSpace(s.substring(1));
else
return s.substring(0, 1) + replaceSpace(s.substring(1));
}

Categories

Resources