Remove punctuation and spaces from String - javascript

The function compress() would accept a sentence and return a string with all the blanks and punctuation removed. This function must call isWhiteSpace() and isPunct().
I've already done the functions to call, but I don't know what's missing from my js code to make it call the functions.
function compress(sent) {
var punc = "; : . , ? ! - '' "" () {}";
var space = " ";
if (punc.test(param)) {
return true
} else {
return false
}
if (space.test(param)) {
return true
} else {
return false
}
isWhiteSpace(x);
isPunct(x);
}

This function must call isWhiteSpace() and isPunct().
So you already have two functions which I assume return true when the passed character is either whitespace or a punctuation mark. Then you need not and should not duplicate this functionality by implementing a duplicate regex based text for whitespace and punctuation in your code. Keep it DRY - don't repeat yourself.
A compress function based on these two functions would look as follows:
function isWhiteSpace(char) {
return " \t\n".includes(char);
}
function isPunct(char) {
return ";:.,?!-'\"(){}".includes(char);
}
function compress(string) {
return string
.split("")
.filter(char => !isWhiteSpace(char) && !isPunct(char))
.join("");
}
console.log(compress("Hi! How are you?"));
I agree that a regex test would probably the to-go choice in a real world scenario:
function compress(string) {
return string.match(/\w/g).join("");
}
However, you specifically asked for a solution which calls isWhiteSpace and isPunct.

You can leverage String.indexOf to design the isPunct function.
function isPunct(x) {
// list of punctuation from the original question above
var punc = ";:.,?!-'\"(){}";
// if `x` is not found in `punc` this `x` is not punctuation
if(punc.indexOf(x) === -1) {
return false;
} else {
return true;
}
}
Solving isWhiteSpace is easier.
function isWhiteSpace(x) {
if(x === ' ') {
return true;
} else {
return false;
}
}
You can put it all together with a loop that checks every character in a string using String.charAt:
function compress(sent) {
// a temp string
var compressed = '';
// check every character in the `sent` string
for(var i = 0; i < sent.length; i++) {
var letter = sent.charAt(i);
// add non punctuation and whitespace characters to `compressed` string
if(isPunct(letter) === false && isWhiteSpace(letter) === false) {
compressed += letter;
}
}
// return the temp string which has no punctuation or whitespace
return compressed;
}

If you return something in a function, execution will stop.
From what I can see, your function doesn't need to return anything... So you should just do this
function compress(sent) {
var punc = ";:.,?!-'\"(){} ";
var array = punc.split("");
for (x = 0; x < array.length; x++) {
sent = sent.replace(array[x], "");
}
isWhiteSpace(x);
isPunct(x);
return sent;
}

Related

Regular expression begin in javascript

I have an input text where user can write string.
I want to have an regular expression in javascript which check if the string starts with three characters FSM.
If the user write another string which doesn't start with FSM, this string was automatically remove and give the error message
Example:
FSMLERTE True
FSMAMAMA True
SFMABNE false et remove this content in the input
I do this but it's doesn't work
var input22Regex= /^[a-z]$/;
if(inputtxt.value.match(inputRegex)) {
return true;
} else {
inputtxt.value = '';
alert("String must start with FSM");
return false;
any idea ?
Try the following:
const testRegex = /^FSM/;
function testString(str) {
if (testRegex.test(str)) {
return true;
} else {
console.log("String must start with FSM");
return false;
}
}
console.log(testString('FSMLERTE')); // true
console.log(testString('FSMAMAMA')); //true
console.log(testString('SFMABNE')); // false
You can use startsWith
if(inputtxt.value.startsWith('FSM')) {
return true;
} else {
inputtxt.value = '';
alert("String must start with FSM");
return false;
}
I think your regex should look like this
/^FSM(.)*/g
You should use /^FSM[A-Z]*/ which will match all inputs that start with FSM and 0 or more capital letters following it. If you want it to be case-insensitive, you can use this instead: /^FSM[A-Z]*/i
var input22Regex = /^FSM[A-Z]*/;
if (inputtxt.value.match(inputRegex)) {
return true;
} else {
inputtxt.value = '';
alert("String must start with FSM");
return false;
}
You can try this regex
FSM[a-zA-Z0-9]+
Demo

Understanding solution of Valid Palindrome in Javascript

This is from LeetCode - Valid Palindrome.
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
while (regex.test(s[start])) {
start++;}
--> can't understand how it works, I understood only that s[start] is alphanumeric characters, it will be false
if (!s[start] || !s[end])
--> What does this mean?
Below is the whole code
var isPalindrome = function(s) {
let regex = /[\W]/;
let start = 0;
let end = s.length - 1;
while (start < end) {
// Moves front runner to next alphanumeric
while (regex.test(s[start])) {
start++;
}
// Moves back runner to next alphanumeric
while (regex.test(s[end])) {
end--;
}
// Above would run until null if there are no alphanumeric characters so return true
if (!s[start] || !s[end]) {
return true;
}
// Check if equal and return false if not
if (s[start].toLowerCase() != s[end].toLowerCase()) {
return false;
}
// If index values match continue the while loop
start++;
end--;
}
return true;
};
Please Advise!
Same as previous solution, plus:
+ removing spaces and symbols, except (A-Z,a-z,0-9)
+ lowercasing
const isPalindrome = function(str) {
const expr = /[\W_]/g;
const lowcaseStr = str.toLowerCase().replace(expr, '');
const reverseStr = lowcaseStr.split('').reverse().join('');
return lowcaseStr === reverseStr
};
This is heavily over-engineered. Why not just use one for loop with 2 counters, one starting at 0 and one at the last index and, while they aren't equal, check if the characters at those indices are the same. Or use built in functions like
function palindrome(str){ return str.split('').reverse().join('') == str}

How to implement a function that will return when an intense string is passed in, and false otherwise?

Strings are intense if they end in three or more more ! marks. However, having ! marks anywhere but the end makes for a non-intense string.
The issue I'm having is when there is an ! in the middle of a string. The result should be false but it's still resulting as true.
My code:
function intenseString (str) {
if (str.slice(-3) !== "!!!") {
return false;
}
else if(str.slice(str.indexOf("!"))){
return false;
}
else if(str.slice(-3) === "!!!"){
return true
}
}
Use indexOf instead of slicing the string:
const strings = ['abc!!!', 'abc!!de', 'abc!']
const intenseString = (str, chars) => str.indexOf(chars) >= 0
console.log(strings.map(x => intenseString(x, '!!!')))
Here's your code, with some formatting tweaks for readability:
function intenseString(str) {
if (str.slice(-3) !== '!!!') {
return false;
}
if (str.slice(str.indexOf('!'))) {
return false;
}
if (str.slice(-3) === '!!!') {
return true;
}
}
Can you give some example inputs that return true? I don't think this will ever return true because the second if statement says "return false if there are any !'s in the string, which is implied by passing the first if.
I believe you meant to add + 1: if (str.slice(str.indexOf('!') + 1)) return false which says "return false if there are any !'s that are not the last character in the string", which still won't work: The first if statement will return false if the string doesn't end with !!! meaning that the smallest string that would get to the second if statement is !!! and there will always be characters after the first !.
Another potential attempt would be to only check the string before the last three characters if (str.slice(0, -3).slice(str.indexOf('!') + 1)) return false, which almost works except for strings containing more than 4 ! at the very end... (such as !!!!!).
I don't see a simple way (without regex to check that the remaining characters are only !) to make the second if statement work without looping over the string.
Note that your final if is unnecessary. Your first two are checking for failure and if they pass through them, it must be an intenseString. Also the string must end in !!! if it got past the first if.
Here's a potential solution which goes through every character in the string, except for the last 4, and returns false if there is ever an ! followed by something that is not an !.
function intenseString(str) {
if (!str.endsWith('!!!')) {
return false;
}
for (let i = 0; i < str.length - 4; i++) {
if (str.charAt(i) === '!' && str.charAt(i + 1) !== ('!')) {
return false;
}
}
return true;
}
Try one of these ways:
function intenseString(str) { return str.slice(-3) === '!!!'; }
function intenseString(str) { return str.endsWith('!!!'); }
function intenseString(str) { return /!{3}$/.test(str); }

Fetching function name and body code from JavaScript file using C#

I need to fetch particular function and its body as a text from the javascript file and print that function as an output using C#. I need to give function name and js file as an input parameter. I tried using regex but couldnt achieved the desired result. Here is the code of regex.
public void getFunction(string jstext, string functionname)
{
Regex regex = new Regex(#"function\s+" + functionname + #"\s*\(.*\)\s*\{");
Match match = regex.Match(jstext);
}
Is there any other way I can do this?
This answer is based on the assumption which you provide in comments, that the C# function needs only to find function declarations, and not any form of function expressions.
As I point out in comments, javascript is too complex to be efficiently expressed in a regular expression. The only way to know you've reached the end of the function is when the brackets all match up, and given that, you still need to take escape characters, comments, and strings into account.
The only way I can think of to achieve this, is to actually iterate through every single character, from the start of your function body, until the brackets match up, and keep track of anything odd that comes along.
Such a solution is never going to be very pretty. I've pieced together an example of how it might work, but knowing how javascript is riddled with little quirks and pitfalls, I am convinced there are many corner cases not considered here. I'm also sure it could be made a bit tidier.
From my first experiments, the following should handle escape characters, multi- and single line comments, strings that are delimited by ", ' or `, and regular expressions (i.e. delimited by /).
This should get you pretty far, although I'm intrigued to see what exceptions people can come up with in comments:
private static string GetFunction(string jstext, string functionname) {
var start = Regex.Match(jstext, #"function\s+" + functionname + #"\s*\([^)]*\)\s*{");
if(!start.Success) {
throw new Exception("Function not found: " + functionname);
}
StringBuilder sb = new StringBuilder(start.Value);
jstext = jstext.Substring(start.Index + start.Value.Length);
var brackets = 1;
var i = 0;
var delimiters = "`/'\"";
string currentDelimiter = null;
var isEscape = false;
var isComment = false;
var isMultilineComment = false;
while(brackets > 0 && i < jstext.Length) {
var c = jstext[i].ToString();
var wasEscape = isEscape;
if(isComment || !isEscape)
{
if(c == #"\") {
// Found escape symbol.
isEscape = true;
} else if(i > 0 && !isComment && (c == "*" || c == "/") && jstext[i-1] == '/') {
// Found start of a comment block
isComment = true;
isMultilineComment = c == "*";
} else if(c == "\n" && isComment && !isMultilineComment) {
// Found termination of singline line comment
isComment = false;
} else if(isMultilineComment && c == "/" && jstext[i-1] == '*') {
// Found termination of multiline comment
isComment = false;
isMultilineComment = false;
} else if(delimiters.Contains(c)) {
// Found a string or regex delimiter
currentDelimiter = (currentDelimiter == c) ? null : currentDelimiter ?? c;
}
// The current symbol doesn't appear to be commented out, escaped or in a string
// If it is a bracket, we should treat it as one
if(currentDelimiter == null && !isComment) {
if(c == "{") {
brackets++;
}
if(c == "}") {
brackets--;
}
}
}
sb.Append(c);
i++;
if(wasEscape) isEscape = false;
}
return sb.ToString();
}
Demo

validating input if starts with "T" or "TP"

I have an input. I need to validate if the value starts with "T" followed by numbers or "TP" followed by numbers
Accepted values: T12345 or TP12345
My JavaScript code
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
alert('It must be start with T');
return false;
} else {
if (v_second_char.toUpperCase !== 'P' && isNaN(Number(v_second_char))) {
alert('error2');
return false;
} else {
return true;
}
}
function myFunction() {
var ip_value = document.getElementById('test').value; //'AB12345';
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
document.getElementById("error").innerHTML = 'It must be start with T';
} else if (v_second_char.toUpperCase() !== 'P' && isNaN(Number(v_second_char))) {
document.getElementById("error").innerHTML = 'error2';
} else {
document.getElementById("error").innerHTML = 'no error';
}
}
It will work on blur <br />
<input type="text" id="test" onblur="myFunction()">
<span id="error">No Error</span>
I think your logic is perfect and should work fine, you just need to change:
v_second_char.toUpperCase
to
v_second_char.toUpperCase()
in last if condition
Final code will be
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var v_first_char = ip_value.substr(0, 1);
var v_second_char = ip_value.substr(1, 1);
if (v_first_char.toUpperCase() !== 'T') {
alert('It must be start with T');
return false;
} else {
if (v_second_char.toUpperCase() !== 'P' && isNaN(Number(v_second_char))) { //change in this line
alert('error2');
return false;
} else {
return true;
}
}
Or for the short line of code you can use the regular expression as shown in above answers.
You can use regular expression to achieve your scenario.
var reg = new RegExp(/^TP?[0-9]+$/)
if((string).match(reg))
return true
else
return false
The condition in the if statement can also be used to retrieve the match string from the original string provided.
Pattern matching against a regular expression would be the best thing to use here. Assuming you are returning true if and only if ip_value is a 'T' or 'TP' followed by at least one number:
var ip_value = document.getElementById('PROMASTER_NO_FW').value;
var pattern = new RegExp(/^TP?\d+$/);
return pattern.test(ip_value);
/^TP?\d+$/ is the regular expression pattern or regex for short - if you're not familiar with regexes, a good starting point in the context of Javascript is the MDN Regular Expressions Guide.

Categories

Resources