Pull number value from string - javascript

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)

Related

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

How to find a word in a string?

The challenge is to "find Waldo." I'm trying to figure out how to find a word in a function/string." Return the index of where in the string 'Waldo' starts."
function findWaldo(str) {
var waldoPosition;
return waldoPosition
}
Simple task to do:
function findWaldo(str) {
return str.indexOf("waldo"); //the string you are looking for
}
It is explained quite well here.
There should be a library that does it easily, like string.indexOf, but you can do it manually with this algorithm:
int count = 0;
string yourText = "This is waldo?";
string toSearch = "waldo";
for (int x = 0; x < yourText.Lenght; x++)
{
if(yourText[x] == toSearch[0])
if((count + 1) == toSearch.Lenght)
return x;
else
count = 0;
//here we'd say ehh there's not Waldo on the string
}
To find a word or letter you can use x.indexOf method, hope to below code helps.
// Question
const findWord = (str, findWord) =>{
let total = ""
let error = false
let errorMessage = "";
if(str != null && str != ""){
error = false
if(!str.indexOf(findWord)){
total = `there is no ${findWord} in str peremeter.
`
}else{
total = `the position of ${findWord} is ${str.indexOf(findWord)}`
}
}else{
error = true;
errorMessage = "Please fill the str perimeter."
return errorMessage
}
return total
}
// Calling Function
console.log(findWord("Hello World", "World"))

Array issues (javascript)

I created a small function that stores the book isbn, it's name and it's author. Everything is fine until I start to print out array. On every entery that completes the object into array, I want it to be printed one after another in new row, but this one is printing the objects from beginning every time when a new object is inserted. How do I fix this?
var books = [];
function blaBla(){
while(isbn != null || name != null || writer != null){
var isbn = window.prompt("Enter ISBN");
var name = window.prompt("Enter name of the book");
var writer = window.prompt("Enter name of the writer");
var patternString = /^[a-zA-Z]+$/;
var patternNum = /^[0-9]+$/;
if(isbn.match(patternNum)){
if(name.match(patternString)){
if(writer.match(patternString)){
books.push({
isbn: isbn,
name: name,
writer: writer
});
}
}
}
for (var i=0; i<books.length; i++){
document.write(books[i].isbn + " - " + books[i].name + " - " + books[i].writer + "</br>");
}
}
}
PS: How do I make it even more "cleaner", so when I hit cancel on prompt, it automatically stops with entering data into array, while, if i stop it on the "writer" prompt, it deletes previous entries for that object (last isbn and last name of the book)?
Thanks in advance.
You might want to give a little more context as to what this function is doing so we can help make your code cleaner as requested. I've separated the collection logic from the display logic here, and also used a while (true) loop with breaks on null or invalid inputs which will stop the collection of data.
Please note that prompt/alert boxes are a hideous way of collecting user input though (very awkward user experience). Consider using a table, input fields, and some jQuery instead to add rows and validate what the user has entered into input boxes.
var books = [];
function collectResponses() {
var patternString = /^[a-zA-Z]+$/;
var patternNum = /^[0-9]+$/;
while (true) {
var isbn = window.prompt("Enter ISBN");
if (!isbn || !isbn.match(patternNum)) {
break;
}
var name = window.prompt("Enter name of the book");
if (!name || !name.match(patternNum)) {
break;
}
var writer = window.prompt("Enter name of the writer");
if (!writer || !writer.match(patternNum)) {
break;
}
books.push({
isbn: isbn,
name: name,
writer: writer
});
}
}
function displayResponses() {
for (var i=0; i<books.length; i++){
document.write(books[i].isbn + " - " + books[i].name + " - " + books[i].writer + "</br>");
}
}

Javascript regular expression difficulty, match string against a name

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

javascript regex, split user's full name

I have user's firstname and lastname in one string, with space between
e.g.
John Doe
Peter Smithon
And now I want convert this string to two string - firstname and lastname
John Doe -> first = John, last = Doe
John -> first = John, last = ""
[space]Doe -> first = "", last = Doe.
I am using next code
var fullname = "john Doe"
var last = fullname.replace(/^.*\s/, "").toUpperCase().trim(); // john
var first = fullname.replace(/\s.*$/, "").toUpperCase().trim(); // Doe
and this works well for two-word fullname. But if fullname has one word, then I have problem
var fullname = "john"
var last = fullname.replace(/^.*\s/, "").toUpperCase().trim(); // john
var first = fullname.replace(/\s.*$/, "").toUpperCase().trim(); // john
http://jsfiddle.net/YyCKx/
any ideas?
Use split + shift methods.
var parts = "Thomas Mann".split(" "),
first = parts.shift(),
last = parts.shift() || "";
So in case of single word name it will give you expected result:
last = "";
Use this code:
You'll need to change the line: splitFullName("firstName","lastName","fullName"); and make sure it includes the right field IDs from your form.
function splitFullName(a,b,c){
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};
document.getElementById(c).oninput=function(){
fullName = document.getElementById(c).value;
if((fullName.match(/ /g) || []).length ===0 || fullName.substring(fullName.indexOf(" ")+1,fullName.length) === ""){
first = fullName.capitalize();;
last = "null";
}else if(fullName.substring(0,fullName.indexOf(" ")).indexOf(".")>-1){
first = fullName.substring(0,fullName.indexOf(" ")).capitalize() + " " + fullName.substring(fullName.indexOf(" ")+1,fullName.length).substring(0,fullName.substring(fullName.indexOf(" ")+1,fullName.length).indexOf(" ")).capitalize();
last = fullName.substring(first.length +1,fullName.length).capitalize();
}else{
first = fullName.substring(0,fullName.indexOf(" ")).capitalize();
last = fullName.substring(fullName.indexOf(" ")+1,fullName.length).capitalize();
}
document.getElementById(a).value = first;
document.getElementById(b).value = last;
};
//Initial Values
if(document.getElementById(c).value.length === 0){
first = document.getElementById(a).value.capitalize();
last = document.getElementById(b).value.capitalize();
fullName = first + " " + last ;
console.log(fullName);
document.getElementById(c).value = fullName;}}
//Replace the ID's below with your form's field ID's
splitFullName("firstName","lastName","fullName");
Source: http://developers.marketo.com/blog/add-a-full-name-field-to-a-marketo-form/
You can use split method
var string = "ad";
var arr = string.split(" ");
var last = arr[0];
var first = arr[1];
if(first == null){
first = "";
}
alert(last + "\n" + first)​;​
If in every situation you have just "first last" you could use:
var string = "john "
var i = string.split(" ");
alert("first: "+i[0]+ "\n"+ "last: " + i[1]);
I know that this has already been replied to and marked as answered but i just want to note that if you do still want to use regex you can change the "last" expression:
var last = string.replace(/^[a-zA-Z]*/, "").toUpperCase().trim();
jQuery( window ).load(function() {
jQuery("#FullNametest").change(function(){
var temp = jQuery(this).val();
var fullname = temp.split(" ");
var firsname='';
var middlename='';
var lastname = '';
firstname=fullname[0];
lastname=fullname[fullname.length-1];
for(var i=1; i < fullname.length-1; i++)
{
middlename = middlename +" "+ fullname[i];
}
jQuery('#FirstName').val(firstname);
jQuery('#LastName').val(lastname);
});
});
var str='John';
var str2='Peter Smithon';
var str3='Peter';
var words=str.split(/\s+/g,2);
var first=words[0];
var last=words[1]||'';
alert(first+' '+last);

Categories