Regular Expression for ignoring a string in javascript - 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);
}

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;
}
}
}

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

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