How to apply special characters in string? - javascript

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)

Related

How to pick only Capital characters from the string?

I am try to pick capital characters from the string with the help of a function and for loop but i can't figure out how i can do it i try using toUpperCase as you see it in the code but it is not work any idea how i can do it ?
function onlyCapitalLetters(cap){
var string = "";
for(var i = 0; i < cap.length; i++){
if(cap[i] === cap.toUpperCase()){
string += cap[i];
}
}
return string;
}
onlyCapitalLetters("Apple");
You can try the regex, with String.prototype.match to return capital letters only:
function onlyCapitalLetters(cap){
return cap.match(/[A-Z]/g, "").join(''); // join the array to return a string
}
console.log(onlyCapitalLetters("Apple"));
console.log(onlyCapitalLetters("BUTTerfly"));
console.log(onlyCapitalLetters("LION"));
Can you try like this
function findUpcase(value){
input = value
data = ""
input.split("").map(res => {
if(res == res.toUpperCase()){
data = data+ res
}
})
return data
}
console.log( findUpcase("MyNameIsVelu") );
//'MNIV'
As noted in comments you need to change cap.toUpperCase() to cap[i].toUpperCase().
But you can do it with just one replace:
console.log('Apple Orange'.replace(/[^A-Z]/g, ""));
It is possible to use replace method with Regex to eliminate numbers and letters written in lowercase:
let str = 'T1eeeEeeeSssssssTttttt';
let upperCase = str.replace(/[a-z0-1]/g, '')
console.log(upperCase);
Please Use Below code to get Capital letter of the sentence :
Demo Code
var str = 'i am a Web developer Student';
var sL = str.length;
var i = 0;
for (; i < sL; i++) {
if (str.charAt(i) != " ") {
if (str.charAt(i) === str.charAt(i).toUpperCase()){
console.log(str.charAt(i));
break;
}
}
}

What is wrong with the logic of my character changing function?

I've tried to create a character changing function for strings, it suppose to change all the "-" to "_", and it only does it for the first character and leaves the rest. If someone could explain it would be grate.
function kebabToSnake(str) {
var idNum = str.length;
for(var i = 0; i <= idNum; i++) {
var nStr = str.replace("-", "_");
}
return nStr;
}
var nStr = str.replace("-", "_");
So, on each iteration, you're replacing the first found - character in the original string, not the string that you've already replaced characters from already. You can either call .replace on just one variable that you reassign:
function kebabToSnake(str) {
var idNum = str.length;
for(var i = 0; i < idNum; i++) {
str = str.replace("-", "_");
}
return str;
}
console.log(kebabToSnake('ab-cd-ef'));
(note that you should iterate from 0 to str.length - 1, not from 0 to str.length)
Or, much, much more elegantly, use a global regular expression:
function kebabToSnake(str) {
return str.replace(/-/g, '_');
}
console.log(kebabToSnake('ab-cd-ef'));

How can I write a function that will format a camel cased string to have spaces?

I need to write a function that will take a string 'camelCased' and then format it to add spaces to it: 'camel Cased'.
You can use regex to split on capitals and then rejoin with space:
.split(/(?=[A-Z])/).join(' ')
let myStrings = ['myString','myTestString'];
function myFormat(string){
return string.split(/(?=[A-Z])/).join(' ');
}
console.log(myFormat(myStrings[0]));
console.log(myFormat(myStrings[1]));
You could replace upper case letters with a leading space.
var string = 'camelCased';
console.log(string.replace(/[A-Z]/g, ' $&'));
I think this will Help
function replaceCamelCase()
{
var op="";
for(int i = 0; i < input.Length; i++)
{
if(isUpper(input.charAt(i))
{
op+=" "+input.charAt(i);
}
op+=input.charAt(i);
}
alert(op);
}
function isUpper(){
if (character == character.toUpperCase())
{
return true;
}
return false;
}

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('')

How do I enhance slugify to handle Camel Case?

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.

Categories

Resources