Javascript regular expression difficulty, match string against a name - javascript

I'm trying to match a name obtained from server against input provided by a user, the complete name may or may not be known entirely by the user, for example I should be able to match the following:
Name Obtained: Manuel Barrios Pineda
Input given: Manuel P
Right until now I've tried with this code:
var name_obtained = 'Manuel Barrios Pineda';
var re = new RegExp('\b[' + name_obtained + ']+\b');
var input_string = 'Manuel';
if (input_string.match(re)) {
alert('Match');
} else {
alert('No Match');
}
Here's an example:
jsfiddle example
EDIT 1:
It's required to match input like 'Manuel B', 'Manuel P'

var name_obtained = 'Manuel Barrios Pineda';
var re = new RegExp('\b[' + name_obtained + ']+\b');
That's not working. Your building a character class to match a single character between word boundaries. The result will be equal to
var re = /\b[adeilnoruBMP]\b/;
input_string.match(name_obtained)
That would never work when the name_obtained is longer than the input_string. Notice that match will try to find the regex in the input_string, not the other way round.
Therefore I'd suggest to use something simple like
var name_obtained = 'Manuel Barrios Pineda';
var input_string = 'Manuel';
if (name_obtained.indexOf(input_string) > -1) {
alert('Match');
} else {
alert('No Match');
}
To use your input_string as a regex to search in the obtained name with omitting middle names or end characters, you could do
String.prototype.rescape = function(save) {
return this.replace(/[{}()[\]\\.?*+^$|=!:~-]/g, "\\$&");
}
var name_obtained = 'Manuel Barrios Pineda';
var input_string = 'Manuel'; // or 'Manuel P', 'Manuel Pineda', 'Manuel B', 'Barrios P', …
var re = new RegExp("\\b"+input_string.rescape().split(/\s+/).join("\\b.+?\\b"));
if (re.test(name_obtained)) {
alert('Match');
} else {
alert('No Match');
}

Perhaps you want something like this
var input_given = 'Manuel P'.replace(/[.+*()\[\]]/g, ' ').replace(/\?/g, '.'),
name_obtained = 'Manuel Barrios Pineda',
arr = input_given.split(' '), i, ret = true;
for (i = 0; i < arr.length && ret; ++i) // for each word A in input
if (arr[i]) // skip ""
ret = new RegExp('\\b' + arr[i]).test(name_obtained);
// test for word starting A in name
// if test failed, end loop, else test next word
if (ret) alert('Match'); // all words from input in name
else alert('No Match'); // not all words found

Related

Pull number value from string

So I need to pull a number value from a string. I currently have a working solution but I feel that maybe I can improve this using a regular expression or something.
Here is my working solution
var subject = "This is a test message [REF: 2323232]";
if(subject.indexOf("[REF: ") > -1){
var startIndex = subject.indexOf("[REF: ");
var result = subject.substring(startIndex);
var indexOfLastBrace = result.indexOf("]");
var IndexOfRef = result.indexOf("[REF: ");
var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);
if(!isNaN(ticketNumber)){
console.log("The ticket number is " + ticketNumber)
console.log("Valid ticket number");
}
else{
console.log("Invalid ticket number");
}
}
As you can see I'm trying to pull the number value from after the "[REF: " string.
// Change of the text for better test results
var subject = "hjavsdghvwh jgya 16162vjgahg451514vjgejd5555v fhgv f 262641hvgf 665115bs cj15551whfhwj511";
var regex = /\d+/g;
let number = subject.match( regex )
console.log(number)
It Will return array for now, and if no match found, it will return null.
For most of the time, when i used this regex i get perfect result unless if string contains decimal values.
var str = 'This is a test message [REF: 2323232]'
var res = str.match(/\[REF:\s?(\d+)\]/, str)
console.log(res[1])
If you don't want to use a regular expression (I tend to stay away from them, even though I know they are powerful), here is another way to do it:
// Your code:
/*var subject = "This is a test message [REF: 2323232]";
if(subject.indexOf("[REF: ") > -1){
var startIndex = subject.indexOf("[REF: ");
var result = subject.substring(startIndex);
var indexOfLastBrace = result.indexOf("]");
var IndexOfRef = result.indexOf("[REF: ");
var ticketNumber = result.substring(IndexOfRef + 6, indexOfLastBrace);
if(!isNaN(ticketNumber)){
console.log("The ticket number is " + ticketNumber)
console.log("Valid ticket number");
}
else{
console.log("Invalid ticket number");
}
}*/
// New code:
const subject = "This is a test message [REF: 2323232]";
const codeAsString = subject.split('[REF: ')[1]
.split(']')
.join('');
if (!isNaN(parseInt(codeAsString))) {
console.log('Valid ticket number: ', parseInt(codeAsString));
}
else {
console.log('Invalid ticket number: ', codeAsString);
}
This will extract number
var subject = "This is a test message [REF: 2323232]";
var onlyNum = subject.replace(/.*(:\s)(\d*)\]$/,'$2');
console.log(onlyNum)
Here, same but the number is now a real int
var subject = "This is a test message [REF: 2323232]";
var onlyNum = parseInt(subject.replace(/.*(:\s)(\d*)\]$/,'$2'));
console.log(onlyNum)

What is the best way to target an array or a string with user input, and log its respective index?

What is the best way to target an array or a string, so that when a user types a letter it finds a match and logs the letter and its index in the array (or the string)?For example (set-up):
GUESS THIS MOVIE:
how to train your dragon
___ __ _____ ____ ______
Type a letter to guess, you have 10 TRIES:
User Typed: o
Result: _o_ _o _____ _o__ ____o_
HERES MY CODE:
var fs = require('fs');
var inquirer = require('inquirer');
var displayProgress = require('./checkGuess');
// var checkGuess = require('./checkGuess');
var PlayFunc = function() {
var blanksArr = [];
var currentWord = [];
this.getData = function() {
var stackOv = "";
fs.readFile("words.txt", "utf8", function(error, data){
if (error) throw error;
dataType = data.toLowerCase();
//data in array
var wordArr = dataType.split(',');
//select random from word from data
var compWord = wordArr[Math.floor(Math.random() * wordArr.length)];//random
//split chosen word
currentWord = compWord.split('');
console.log("========================\n\n\n");
//Looping through the word
for (var i = 0; i <= currentWord.length - 1; i++) {
// pushing blanks
var gArr = blanksArr.push("_");
//HYPHENS, COLONS, SPACES SHOULD BE PASSED
stackOv = currentWord.join("").replace(/[^- :'.]/g, "_");
wordString = currentWord.join("");
}
console.log("GUESS THIS MOVIE: ");
fs.writeFile("blanks.txt", stackOv, (err) => {
if (err) throw err;
console.log(wordString);
fs.readFile('blanks.txt', "utf8",(err, word) => {
if (err) throw err;
// console.log("GUESS THIS MOVIE: " + compWord);
blanksTxt = word.split(''); //console.log(string.join('').replace(/[^-: '.]/g, "_"));
displayProgress = new displayProgress();
displayProgress.checkGuess();
});
});
});
}
}
module.exports = PlayFunc;
ON THE NEXT FILE CALLED checkGuess.js I Plan to do the checking (which goes back to my original question (OP).
var fs = require('fs');
var inquirer = require('inquirer');
var PlayFunc = require('./PlayFunc');
var displayProgress = function (){
// console.log("WORKING CONNECTED CHECKGUESS MODULE");
// PlayFunc = new PlayFunc();
// PlayFunc.getData();
var a = blanksTxt.join(''); console.log(a); //string a
var manipulateThisArray = blanksTxt;//reading from blanks.txt
// console.log(manipulateThisArray);
this.checkGuess = function(){
inquirer.prompt([
{
type: "input",
name: "letter",
message: "Type a letter to guess, you have 10 TRIES:"
}
]).then(function(userInput) {
var correctArray = [];
// console.log(userInput.letter);
letterTyped = userInput.letter;
//logic
//test if we can parse through the array
for (var i = 0; i <= manipulateThisArray.length - 1; i++) {
x = manipulateThisArray[i]; console.log(x);
// if userinput letter-value matches chosen words letter value
// replace this chosen worsa letter with userinput value
// if(letterTyped == x.charAt(i)) {
console.log("THERES A MATCH " + x.charAt(i));
// }else {
// console.log("NO MATCH");
// }
}
});
}
}
// checkGuess();
module.exports = displayProgress;
//declaration of the variables we need
//the original string:
const string = "how to train your dragon";
//a string of characters we want to show
const show = "o";
//A resulting string we can work with
var result = "";
//Now we go over every character of our string and
for(const character of string){
//check if the character is inside the characters we want to show
if(show.includes(character)){
//if so we show it by adding it to the result
result += character;
}else{
//If not we add an _ instead
result += "_";
}
}
//At the end we can show the result
alert(result);
For this i would use the 'foo'.replace('bar', 'bar') and make sure that the String contains the input 'foo'.includes('input') also you could use a RegExp.
To get the index you could do a loop through the length of the String and use the 'foo'.indexOf('input', number) that will return -1 if no coincidence

Google Apps Script Auto Capitalise

I have been struggling with a script I have been working on for a while. The problem is that when I run the script with text like:
Hi. apples are amazing.
I want to make only the a in apples capitalized, but instead the text comes out as:
Hi. Apples Are Amazing.
Here is the code:
function caps()
{
var body = DocumentApp.getActiveDocument().getBody();
var text = body.editAsText()
var caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lower = "abcdefghijklmnopqrstuvwxyx";
//while (() != null) {
//var search = text.findText('. a')
//var start = replace - 1
//text.deleteText(start, replace)
//text.insertText(start, " A")//}
for(var i=0; i<caps.length; i++)
{
var nextCaps = caps.charAt(i);
var nextLower = lower.charAt(i);
while (text.findText('. ' + nextLower) != null)
{
Logger.log(nextLower)
Logger.log(nextCaps)
var search = text.findText('. ' + nextLower)
var replace = search.getEndOffsetInclusive()
var start = replace - 1
text.deleteText(start, replace)
text.insertText(start, " " + nextCaps)
}
//var nextChar = caps.charAt(i);
//Logger.log(nextLower)
}
}
Basically, the code looks for ". a" and replaces it with ". A" (same with b, c, d and so on). If anyone can help me with this it would be very much appreciated.
The below code follows your example where you want to capitalize the first letter after the end of the first sentence. So long as that is the case this regex and replace will do that for any letters.
var str = 'Hi. apples are amazing.';
var reg = /\.\s./;
function replacement(match) {
return match.toUpperCase();
}
str = str.replace(reg, replacement);
Logger.log(str);

Limiting length of each word in a string

Is there a way to limit the length of each word in a string?
For example:
Loop through each word in a string
If a word is longer than X amount of characters, display a pop up message and do not submit the form.
Edit: My final code:
$("#comment-form").submit(function(event) {
var str = $("#comment-box").val(), limit = 135;
var wordList = str.split(' ');
$(wordList).each(function(i, word) {
if(word.length > limit) {
alert("Your comment has a string with more than " + limit + " characters. Please shorten it.");
event.preventDefault();
}
});
});
Try this:
var str = "This is the test string that contains some long words";
var wordList = str.split(' ');
var limit = 4;
$(wordList).each(function(i, word){
if(word.length >= limit){
alert(word);
}
});
You can use the following function
<script>
var string = "Please be sure question to answer the question";
function checkWordLength(string)
{
var string_array = string.split(" ");
for(var i=0; i<string_array.length; i++)
{
var word = string_array[i];
var word_length = word.length;
if(word_length>6) return false;
}
}
checkWordLength(string);
</script>
jsFiddle
function CheckString(string, character_limit)
{
var word = /\w+/igm;
var match;
while((match = word.exec(string)) !== null) {
if(match[0].length > character_limit)
{
alert(match[0]);
return false;
}
}
return true;
}
var character_limit = 5;
var string = 'this is a string of words and stuff even';
CheckString(string, character_limit);
This example uses regular expressions when it returns false make sure to either return false from the onSubmit method of your form.

Count BB code occurence

I want to count number of occurence of BB code like word (example: [b] [/b]).
I tried
(str.match(/\[b\]/g) str.match(/\[\/b\]/g))
None of this worked, please help !!!
Edit
document.getElementById('textarea').value = 'HIiiiiiiiiiii [b]BOld[/b]';
var str = document.getElementById('textarea').value;
Answer:
if (str.match(/\[b\]/g).length == str.match(/\[\/b\]/g)).length) {alert("Fine");}
This regex will match a BB code opening tag:
str.match(/\[[a-z]*\]/g)
Edit: Here's some code that will do exactly what you want including creating an array of errors listing all missing closing tags. This code uses the underscore library for the groupBy() call.
jsFiddle
var bbcode = 'HI[i]iii[i]iii[/i]iii [b]BOld[/b] yahhh [img]url[/img]';
var matches = bbcode.match(/\[[a-z]*\]/g); //get the matches
var tags = _.groupBy(matches, function(val) {
val = val.substring(1, val.length-1);
return val;
});
var errors = [];
for (var tag in tags) {
var regex = '\\\[/' + tag + '\\\]';
if (bbcode.match(regex).length != tags[tag].length) {
errors.push('Missing a closing [/' + tag + '] tag');
}
}
console.log(errors);
Replace occurences until there aren't any; keep track of the amount on the way:
var regexp = /\[[a-z]\](.*?)\[\/[a-z]\]/i;
var str = "test [b]a[/b] test [i]b[/i] [b]d[/b] c";
var newstr = str;
var i = 0;
while(regexp.test(newstr)) {
newstr = newstr.replace(regexp, "");
i++;
}
alert(i); // alerts 3

Categories