How to remove everything from string after the last character? - javascript

I am practicing and I wrote length of last word in JS.
var lengthOfLastWord = function (s) {
var words = s.split(" ");
var len = words.length;
for (let i = 0; i < len; i++) {
if (len == 1){
var last_element = words[0];
}
else {
var last_element = words[len - 1];
}
return last_element.length;
}
}
But it doesn't work well if
s = 'a '
or
s = 'Hello.'
How to write substring to remove everything except characters?

I would suggest you to try the following code:
s = 'Hello. '
s.trim();
The trim() function removes all whitespaces from your String.

You can use regex to replace charachters those are not in a-z or A-Z or 0-9. or simply just use \W in regex expression :
var last_element = words[len - 1].replace(/\W/g, "");

Related

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

Split a string using regex

I have a string and I want is split into an array so that it is split by '+' unless it is inside brackets
E.g. the string
"abc+OR+def+OR+(abc+AND+def)"
becomes
["abc", "OR", "def", "OR", "(abc+AND+def)"]
and the string
"(abc+AND+cde)+OR+(abc+AND+(cde+AND+fgh))"
becomes
["(abc+AND+cde)", "OR", "(abc+AND+(cde+AND+fgh)"]
Is it possible to do this using regular expressions?
You can do this with regex, but only with that languages that support recursive regular expression (for example, perl or any language wit PCRE).
It is not easy with JavaScript regexes, because they do not support recursion.
But it is possible using XRegExp using additional plugin:
http://xregexp.com/plugins/#matchRecursive
Also please check these two links:
http://blog.stevenlevithan.com/archives/regex-recursion
http://blog.stevenlevithan.com/archives/javascript-match-nested
I don't think you could do this with regex. EDIT: per Silver, you could use regex.
One way would be to just parse the string character by character. I'll edit my answer with code in a minute.
EDIT: Here's a sample implementation (note: untested, may have a bug or two):
function parseString (str) {
var splitStr = [], parentheses = 0, i = 0
for (var j = 0; j < str.length; j++) {
if (str[j] == '+' && !parentheses)
i++
else if (str[j] == '(')
parentheses++
else if (str[j] == ')')
parentheses--
else
splitStr[i] += str[j]
}
return splitStr
}
You can use the match method of String object to do this and use the following regex:
stringObj.match(/([a-zA-Z]+)|([(]([a-zA-Z]+[+])+[a-zA-Z]+[)])+/gi);
This regular expression would suit your needs.
(?!=\([\w\+]+)\+(?![\w+\+]+\))
See it in action here.
There is one small problem: Negative lookbehind (?!=...) is not implemented in the javascript regular expression parser.
For anyone who is learning regular expressions, here is a walkthrough:
(?!=\([\w\+]+) is a negative lookbehind. It means "not preceeded by ..." In this case, we're looking for something not preceeded by (lettersOr+.
\+ is what we are looking for. A plus sign (escaped)
(?![\w+\+]+\)) is a negative lookahead. It means "not followed by ..." In this case, we're looking for something not followed by lettersOr+)
This function should work for you:
var PARENTH_STRING_PLACE_HOLDER = '__PARSTRINGHOLDER__';
var splitPlusNoParenthesis = function(str){
//Replace the parenthStrings with the placeholder
var parenthStrings = getParenthesizedStrings(str);
for(var i = 0; i < parenthStrings.length; i++){
str = str.replace(parenthStrings[i], PARENTH_STRING_PLACE_HOLDER);
}
//Split on '+'
var splitString = str.split('+');
//Replace all placeholders with the actual values
var parIndex = 0;
for(var i = 0; i < splitString.length; i++){
if(splitString[i] === PARENTH_STRING_PLACE_HOLDER){
splitString[i] = parenthStrings[parIndex++];
}
}
return splitString;
};
var getParenthesizedStrings = function(str){
var parenthStrings = [];
for(var startIndex = 0; startIndex < str.length; startIndex++){
if(str[startIndex] === '('){
var parenthCount = 1;
var endIndex = startIndex + 1;
for(; endIndex < str.length; endIndex++){
var character = str[endIndex];
if(character === '('){
parenthCount++;
} else if(character === ')'){
parenthCount--;
}
if(!parenthCount){
parenthStrings.push(str.substring(startIndex, endIndex + 1));
break;
}
}
startIndex = endIndex;
}
}
return parenthStrings;
};
Here's a fiddle to test.

How can i match and replace a string and its before one letter in javascript?

var str="itss[BACK][BACK][BACK][BACK][BACK][BACK] it's a test stringgg[BACK][BACK]";
var word = '[BACK]';
var substrings = str.split(word);
var cnt= substrings.length - 1;
for(var i = 0;i<cnt;i++){
str = str.replace(/.{1}\[BACK\]{1}/i,""); //remove backspace and one character before it.
}
The above script returns something like "[BACK it's a test string" I need to get this result as "it's a test string" please help me....
It's easier to do this without a regex actually.
String.prototype.replaceFromIndex=function(index, length, replace) {
return this.substr(0, index) + replace + this.substr(index+length);
}
var search = '[BACK]';
var str="itss[BACK][BACK][BACK][BACK][BACK][BACK] it's a test stringgg[BACK][BACK]";
while((index = str.indexOf(search)) >= 0){
str = str.replaceFromIndex(index-1, search.length+1, '');
}
alert(str);
Check http://jsfiddle.net/fRThH/2/ for a working example.
Wrap it in a function and you are ready to go!
Courtesy to Cem Kalyoncu ( https://stackoverflow.com/a/1431113/187018 ) for a slightly modified version of String.prototype.replaceAt
My idea is to count all the backspaces [BACK] and then replace them with an empty string one by one:
var str="itss[BACK][BACK][BACK][BACK][BACK][BACK] it's a test stringgg[BACK][BACK]";
var backspaces = str.match(/\[BACK\]/g).length;
for(i=0; i<backspaces; i++)
{
str = str.replace(/.?\[BACK\]/, '');
}
document.write( str );
working example: jsFiddle
If I understood correctly
var dat = str.split('[BACK]').filter(function(e){return e})[1];
here is the working demo.
One of the problems that I found out was that you didn't set a condition in which you would not have to remove the first character when the string '[BACK]' is in position zero.
Well, the solution I am posting here first search for the position of the first '[BACK]' string, and then creates a substring of the characters that we want to remove, so, if there is a character before the string '[BACK]', it is included in the substring. Then, the substring is removed from the main string, and it continues looping until all the '[BACK]' s are removed.
var str = "itss[BACK][BACK][BACK][BACK][BACK][BACK] it's a test stringgg[BACK][BACK]";
var word = '[BACK]';
var substrings = str.split(word);
var cnt = substrings.length - 1;
for (i = 0; i < cnt; i++) {
pos = str.search("[BACK]");
if (pos - 1 > 0) {
str = str.replace(str.substring(pos - 2, pos + 5), '');
} else {
str = str.replace(str.substring(pos - 1, pos + 5), '');
}
}
Here is the code in jsfiddle:

How do i get numbers from this string?

i have this string:
var s = 'http://xxxxxxx.xxx/abcd123456789?abc=1';
how do i get digits 123456789 (between "d" and "?") ?
these digits may vary. the number of digits may vary as well.
How do i get them?? Regex? Which one?
try
'http://xxxxxxx.xxx/abcd123456789?abc=1'.match(/\d+(?=\?)/)[0];
// ^1 or more digits followed by '?'
Try
var regexp = /\/abcd(\d+)\?/;
var match = regexp.exec(input);
var number = +match[1];
Are the numbers always between "abcd" and "?"?
If so, then you can use substring():
s.substring(s.indexOf('abcd'), s.indexOf('?'))
If not, then you can just loop through character by character and check if it's numeric:
var num = '';
for (var i = 0; i < s.length; i++) {
var char = s.charAt(i);
if (!isNaN(char)) {
num += char;
}
}
Yes, regex is the right answer. You'll have something like this:
var s = 'http://xxxxxxx.xxx/abcd123456789?abc=1';
var re = new RegExp('http\:\/\/[^\/]+\/[^\d]*(\d+)\?');
re.exec(s);
var digits = $1;

Stripping some characters out of a string

I try to remove some non-safe characters from a string but i believe i have a problem on my RegExp object.
What i try to do below is if there are chars whose encoded length is greater than 3 chars they should be replaced with a space.
So if encoded value is %3D which is = sign, it is ok to have in my string. But if it is an ’ apostrophe %E2%80%99 it should be replaced with a space.
val = "Angelina’s";
valEnc = encodeURIComponent(val);
for(var i = 0; i < val.length; i++){
var a = val.substr(i,1);
if(encodeURIComponent(a).length > 3){
console.log(a, encodeURIComponent(a));
var re = new RegExp(encodeURIComponent(a),"ig");
valEnc.replace(re," ");
};
};
console.log(decodeURIComponent(valEnc));
This code works and logs me the unwanted chars but it can not replace them with spaces, what am i doing wrong? Thanks.
You seem to be using regular expressions unnecessarily here. One way to do this is to build up the result string one character at a time:
val = "Angelina’s";
valEnc = "";
for(var i = 0; i < val.length; i++){
var a = val.substr(i,1);
var e = encodeURIComponent(a);
if(e.length <= 3){
valEnc += e;
}
}
console.log(decodeURIComponent(valEnc));

Categories

Resources