Need to strip a leading character (# or +) from this string - javascript

In the cases below I need to strip either the first "#" or "+" character for vars b & c so they can become vars a & a1 which are used to be a string in a new url that's built elsewhere.
Here is the code:
var b = "http://www.somewhere.com/search/#foo+bar+baz"
var c = "http://www.somewhere.com/search/++bar+baz"
var a = b.split("/")[4].split("+").slice(0, 1);
var a1 = c.split("/")[4].split("+").slice(0, 1);
Here is the fiddle.

This works for me on your fiddle.
var b = "http://www.somewhere.com/search/#foo+bar+baz"
var c = "http://www.somewhere.com/search/++bar+baz"
var a = b.split("/")[4].split("+").slice(0, 1);
if(a[0].indexOf('#') != -1){a = a[0].split('#')[1]}
var a1 = c.split("/")[4].split("+");
var i=0;
while(true){
if(a1[i] != ''){a1 = a1[i]; break;}
i++;
}
$("#result").html(a);
$("#result2").html(a1);
console.log(a);
console.log(a1);

Updated your fiddle
You can replace the first occurrence of a char with using a regex quite easily:
var a = b.replace(/[#+]/,'');
var a1 = c.replace(/[#+]/,'');
Without the g modifier it will only replace the first one it finds.

Related

Replace character of a string with the character from an array

I'm trying to make a script that changes text into these cool looking letters, it looks like everything should be working but when I try to send the replaced message it gives me a character like a white question mark on a black background. This: �
Here's the code:
var mm = "test";
var alphabet = "🇦🇧🇨🇩🇪🇫🇬🇭🇮🇯🇰🇱🇲🇳🇴🇵🇶🇷🇸🇹🇺🇻🇼🇽🇾🇿";
var nalphabet = "abcdefghijklmnopqrstuvwxyz";
for(var z in mm){
var x = nalphabet.indexOf(mm[z].toLowerCase());
var ool = alphabet[x];
msg.channel.sendMessage(ool);
}
This is all about the coding of characters. Each of your cool-looking letters has length 2. So when you try to get such character directly by index, you receive just a half of it. As a solution you can try to join two sibling characters. Something like this
var mm = "test";
var alphabet = "🇦🇧🇨🇩🇪🇫🇬🇭🇮🇯🇰🇱🇲🇳🇴🇵🇶🇷🇸🇹🇺🇻🇼🇽🇾🇿";
var nalphabet = "abcdefghijklmnopqrstuvwxyz";
for(var z in mm){
var x = nalphabet.indexOf(mm[z].toLowerCase());
var ool = alphabet[x * 2] + alphabet[x * 2 + 1];
msg.channel.sendMessage(ool);
}
Try this one:
var message = "test";
var alphabet = ["🇦","🇧","🇨","🇩","🇪",
"🇫","🇬","🇭","🇮","🇯",
"🇰","🇱","🇲","🇳","🇴",
"🇵","🇶","🇷","🇸","🇹",
"🇺","🇻","🇼","🇽","🇾","🇿"];
var nalphabet = "abcdefghijklmnopqrstuvwxyz";
for(var letter in message) {
var x = nalphabet.indexOf(message[letter].toLowerCase());
var ool = alphabet[x];
document.write(ool);
}
Here is a Fiddle.

Manipulate replace string in javascript

I have three variables in javascript like
var a = document.getElementById("txtOrderNumberRelease1").value;
var b = document.getElementById("txtOrderNumberRelease2").value
var c = document.getElementById("ddlOrderNumberRelease3");
and
var mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY"
In mainString, the value "789" is coming from variable "a",
value "456" is coming from variable b and value "LLX" is coming from variable "c".
Variables "a" and "b" will always be Integers, whereas variable "c" will always be one the three values ie. "LLI,LLA,LLX".
Before value "789", there can be any number of words splitted by hypen "-". like ROAM-LCD-Synergy-SSI etc...
But after the value of variable "c" i.e "LLX" in mainString, there can be only one word for eg. "WARRANTY".
Now my issue is, I have to replace these three values of "a","b" and "c" ie. "789-456-LLX" with my newly entered values lets say 987-654-LLA, then my desired final string would be
old string: mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY"
desired string: mainString ="ROAM-LCD-Synergy-987-654-LLA WARRANTY"
Please suggest some wayout.
Thanks
var a = 123;
var b = 456;
var c = "ABC";
var mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY";
var updatedString = mainString .replace(/\d{3}-\d{3}-[A-Z]{3}\s([^\s]*)$/,a+"-"+b+"-"+c+" $1");
console.log(updatedString);
Something like this should work:
mainString.replace(/[\d]{3}\-[\d]{3}\-[\w]{3}\s([\w]+)$/, a + "-" + b + "-" + c + " $1");
Here's an option that uses string.split.
function replaceLastThreeDashedFields(original,a,b,c) {
var spaceSplit = original.split(' ');
var dashSplit = spaceSplit[0].split('-');
dashSplit[dashSplit.length - 3] = a;
dashSplit[dashSplit.length - 2] = b;
dashSplit[dashSplit.length - 1] = c;
var newDashed = dashSplit.join('-');
spaceSplit[0] = newDashed;
var newSpaced = spaceSplit.join(' ');
return newSpaced;
}
Just change the values before they are assigned? Place this before your variables are declared.
document.getElementById("txtOrderNumberRelease1").value = '987';
document.getElementById("txtOrderNumberRelease2").value = '654';
document.getElementById("txtOrderNumberRelease3").value = 'LLA';
The following code should update based on the values of a, b, and c...
var mainString ="ROAM-LCD-Synergy-789-456-LLX WARRANTY";
var a = document.getElementById("txtOrderNumberRelease1").value;
var b = document.getElementById("txtOrderNumberRelease2").value;
var c = document.getElementById("ddlOrderNumberRelease3");
mainString = mainString.replace("789",a);
mainString = mainString.replace("456",b);
mainString = mainString.replace("LLX",c);

JavaScript get character in sting after [ and before ]

I have some strings like:
str1 = "Point[A,B]"
str2 = "Segment[A,B]"
str3 = "Circle[C,D]"
str4 = "Point[Q,L]"
Now I want to have function that gives me character after "[" and the character before "]". How could I make something like that ?
try this one...
var str = "Point[A,B]";
var start_pos = str.indexOf('[') + 1;
var end_pos = str.indexOf(']',start_pos);
var text_to_get = str.substring(start_pos,end_pos)
alert(text_to_get);
You'd need regex to do that
var matches = /\[(.*?)\]/.exec(str1);
alert(matches[1]);
You can use match() to extract the characters:
str.match(/\[(.*)\]/)[1]
A safer way would be:
var matches = str.match(/\[(.*)\]/);
if(matches) {
var chars = matches[1];
}
Here's an approach which avoids regex.
var str = "Point[A,B]";
var afterOpenBracket = str.split("[")[1]; // returns "A,B]"
var bracketContents = afterOpenBracket.split("]")[0]; // returns "A,B"
There, pretty simple! bracketContents now contains the entirety of the text between the first set of brackets.
We can stop here, but I'll go a step further anyway and split up the parameters.
var parameters = bracketContents.split(","); // returns ["A", "B"]
Or in case u have more [A,C,D,B] and don't want to use regex:
var str1 = "Point[A,C,D,B]";
function extract(str1){
var a = str1.charAt(str1.indexOf('[')+1);
var b = str1.charAt(str1.indexOf(']')-1);
return [a, b];
//or
//a.concat(b); //to get a string with that values
}
console.log(extract(str1));

Global Replace with js

I have the following string:
[27564][85938][457438][273][48232]
I want to replace all the [ with ''. I tried the following but it didn't work:
var str = '[27564][85938][457438][273][48232]'
var nChar = '[';
var re = new RegExp(nChar, 'g')
var visList = str.replace(re,'');
what am I doing wrong here?
Many thanks in advance.
You need to escape the [ otherwise it is interpreted as the start of a character class:
var nChar = '\\[';
If nChar is a variable (and I assume it is otherwise there would be little point in using RegExp instead of /.../g) then you may find this question useful:
Is there a RegExp.escape function in Javascript?
var string = "[27564][85938][457438][273][48232]";
alert(string.replace(/\[/g, '')); //outputs 27564]85938]457438]273]48232]
I escaped the [ character and used a global flag to replace all instances of the character.
I met this problem today.
The requirement is replace all "c++" in user input string. Because "+" has meaning in Reg expression, string.replace fails.
So I wrote a multi-replace function for js string. Hope this can help.
String.prototype.mreplace = function (o, n) {
var off = 0;
var start = 0;
var ret = "";
while(true){
off = this.indexOf(o, start);
if (off < 0)
{
ret += this.substring(start, this.length);
break;
}
ret += this.substring(start, off) + n;
start = off + o.length;
}
return ret;
}
Example:
"ababc".mreplace("a", "a--"); // returns "a--ba--bc"

Merging the Strings

HI ,
In Java Script ,
var a ="apple-orange-mango"
var b ="grapes-cheery-apple"
var c = a + b // Merging with 2 variable
var c should have value is "apple-orange-mango-grapes-cheery" .Duplicated should be removed.
Thanks ,
Chells
After your string is combined, you will want to split it using the delimiters (you can add these back in later).
example:
var a ="apple-orange-mango"
var b ="grapes-cheery-apple"
var c = a + "-" + b
var Splitted = c.split("-");
the Splitted variable now contains an array such as [apples,orange,mango,grapes,cherry,apple]
you can then use one of many duplicate removing algorithms to remove the duplicates. Then you can simply do this to add your delimiters back in:
result = Splitted.join("-");
Here's a brute force algorithm:
var a;
var b; // inputs
var words = split(a+b);
var map = {};
var output;
for( index in words ) {
if( map[ words[index] ]!=undefined ) continue;
map[ words[index] ] = true;
output += (words[index] + '-');
}
output[output.length-1]=' '; // remove the last '-'
The map acts as a hashtable.
Thats it!
I don't know if it is an homework.
By the way you can split strings like a and b with the split method of string object.
in your case:
firstArray=a.split("-");
secondArray=b.split("-");
the removal of duplicates is up to you...
In your simple example, just use var c = a + "-" + b;
If you want duplicates removed, split a and b into arrays, and combine them, like so:
var avalues = a.split("-");
var bvalues = b.split("-");
var combined = avalues.concat( bvalues );
// now loop over combined and remove duplicates

Categories