I have a code that simply compares str2 (User input) with str1 (our reference string ) to check if any word in str2 is typed wrongly or correctly. The code works fine but I can't find a solution to this problem:
I want to ignore extra spaces, commas and dots and any other writing signs to be compared in both strings. just like a dictation app...
for example, below strings should assume as equal strings on output:
str1 = "I was sent to earth"
str2 = "I was, sent to: earth."
Any other modifications to improve this code is extremely appreciated.
Please Help...
var str1 = "I was sent to earth to protect my cousin";
var str2 = "I waz Sent to earth to protet my cousine";
let a = str1.toLowerCase().split(' ');
let b = str2.toLowerCase().split(' ');
let res1 = b.filter(i => !a.includes(i));
let res2 = a.filter(i => !b.includes(i));
console.log(res1);
console.log(res2);
var str1 = res1.toString();
str1 = str1.replace(/,/g, '\n');
var str2 = res2.toString();
str2 = str2.replace(/,/g, '\n');
var player = GetPlayer();
player.SetVar("wrong_Spell",str1);
player.SetVar("right_Spell",str2);
You could use match to extract the words using \w+:
function words(s) {
return s.toLowerCase().match(/\w+/g);
}
var str1 = "I was sent to earth to protect my cousin";
var str2 = "I waz Sent to earth to protet my cousine";
let a = words(str1);
let b = words(str2);
let res1 = b.filter(i => !a.includes(i));
let res2 = a.filter(i => !b.includes(i));
console.log(res1);
console.log(res2);
Related
The Code below search a particular word (best) in a sentence and return true or false depending on the result.
Now I need to upgrade to allow it search for mulptiple words Eg. "site, all, world"
var myString = 'Stackoverflow is the best site for all developers in the world';
var multiple_Word = 'best';
var a = new RegExp('\\b' + multiple_Word + '\\b');
alert (a.test(myString)); // false
You can extend your code and change it to a function.
var myString = 'Stackoverflow is the best site for all developers in the world';
function search(input){
var a = new RegExp('\\b' + input + '\\b');
return a.test(myString)
}
console.log(['site', 'all', 'world', 'blah blah'].some(e=>search(e)))
You can use join as in comment you mentioned you want to match one these.
var myString = 'Stackoverflow is the best site for all developers in the world';
const words1 = ['best', 'site', 'random'];
let reg = `\b${words1.join('|')}\b`
let regex = new RegExp(reg)
console.log(regex.test(myString))
There is a good regex resource here: https://regex101.com/
Added blah to demonstrate.
var myString = 'Stackoverflow is the best site for all developers in the world';
var multiple_Word = 'best|BLAH|world';
var a = new RegExp('\\b' + multiple_Word + '\\b');
alert (a.test(myString)); // false
Use Array#join with |
const str = 'Stackoverflow is the best site for all developers in the world';
const words1 = ['best', 'site', 'random'];
const words2 = ['will', 'fail', 'always'];
const a = new RegExp('\\b' + words1.join("|") + '\\b');
const b = new RegExp('\\b' + words2.join("|") + '\\b');
console.log(a.test(str));
console.log(b.test(str));
Here is example of doing this with includes()
let words = ["the","best","world"];
let words2 = ["the","best","world","apple"];
var myString = 'Stackoverflow is the best site for all developers in the world';
function checkWords(str,words){
for(let word of words){
//if the word in words arr doesnot exist is str it will return false
if(!str.includes(word)) return false
}
//if false is not return in loop it means all words exist is str so return true
return true;
}
console.log(checkWords(myString,words));
console.log(checkWords(myString,words2));
I'm trying to split a sentence by removing a certain word
for example:
var word = "am";
var sentence = "Hello am I John?";
var stringpart2 = sentence.split(" ");
var stringpart1 = stringpart2.splice(0,stringpart2.indexOf(word));
stringpart2.remove(word);
stringpart1.remove(word);
var istring1 = stringpart1.toString();
var finalpart1 = istring1.replace(/,/g, " ");
var istring2 = stringpart2.toString();
var finalpart2 = istring2.replace(/,/g, " ");
now this works as it returns this:
finalpart1 = "Hello I"
finalpart2 = "John?"
but when I make the word the last word in the sentence:
var word = "John";
it returns
finalpart1 = ""
finalpart2 = "Hello am I John?"
Anyone have any idea how to fix this so its like this:
finalpart1 = "Hello am I?"
finalpart2 = ""
It might be worth mentioning I'm taking the word and the sentence out of an array that I get through $.getJSON and if the word is the first word of the sentence it works just fine.
You may use the following regular expression:
function replace(text, word) {
return text.replace(new RegExp('\\s\\b' + word + '|' + word + '\\b\\s'), '')
}
const text = 'Hello am I John?'
console.log( replace(text, 'Hello') )
console.log( replace(text, 'am') )
console.log( replace(text, 'John') )
You can split directly by the word:
var splitted = sentence.split(word);
console.log(splitted[0], splitted[1], etc...);
In this case if you split by John it will look exactly like you want.
Here is my String:
var str1 = '#hello, world how are you. I #am good';
Now I want to split # prefixed worlds like #hello, #am etc to be stored in an array.
Desired output will be
var str2 = [#hello, #am];
can anyone guide me.
With a simple regex
\B#\w+/g
without a function :
var str1 = '#hello, world how are you. I #am good';
console.log(str1.match(/\B#\w+/g));
with a function :
getMatchedStrings("#hello, #world how are you. I #am good");
function getMatchedStrings(input){
var re = /\B#\w+/g;
var specials = [];
var match;
while(match = re.exec(input)){
specials.push(match[0]);
}
console.log(specials)
}
You may try more regex here :
https://regex101.com/r/rBuMrY/1
Output:
["#hello", "#am"]
Check this out, i add comment for easy understand this code
var str = '#hello, world how are you. I #am good';
str = str.split(' '); // split text to word array
str = str.filter(function(word){
return word.includes('#'); // check words that using #
}).map(function (word) {
return word.replace(/[^a-zA-Z^# ]/g, "") // remove special character except #
});
console.log(str) // show the data
var str1 = '#hello, world how are you. I #am good';
var reg = /(?:^|[ ])#([a-zA-Z]+)/;
var str = str1.split(" ");
//console.log(str.length);
for (var i = 0; i < str.length; i++) {
if (reg.test(str[i])) {
//your code to store match value in another array
console.log(str[i]);
}
}
Use Regex, I am not really good at it but just a try
var str1 = '#hello, world how are you. I #am good';
var str2 = str1.match(/#(.+?)[^a-zA-Z0-9]/g).map(function(match) { return match.slice(0, -1); });
console.log(str2);
i have problems inserting character in result of regex. I need do some like this:
var str = "Hello world, hello";
var regX = /he/ig;
The result have to be a string like this:
console.log(result);
<mark>He</mark>llo world, <mark>he</mark>llo"
I tried using this code:
r = /he/ig;
str = "Hello world Hello";
var match, indexes = [];
while (match= r.exec(str)){
indexes.push([match.index, match.index+match[0].length]);
}
indexes.forEach( (element) => {
var strStart = str.substring(0,element[0]);
var strBetween = "<mark>"+str.substring(element[0],element[1])+"</mark>";
var strEnd = str.substring(element[1],str.length);
str = strStart.concat(strBetween,strEnd);
});
console.log(str); //<mark>He</mark>llo worl<mark>d </mark>Hello
I understand where is the error, but i don't kwon how solve that.
You can do this with the .replace() method:
var str = "Hello world hello";
var result = str.replace(/he/ig, "<mark>$&</mark>");
The $& in the replacement string means that the matched text should be substituted.
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));