Regex to with a starting letter AND it contains a word - javascript

var str = "I dont have any one";
var str1 = "We dont have any one";
var str2 = "I dont have any more";
var str2 = "I dont have any two";
for these string need to find a reg like it should match string starts with "I" AND contains "one" or "two".
var regx = "/^I/"; //this starts with I
var regx = "/(one|two)/"; //this match one or two
But how to combain both with an AND ?
So str1.test(regx) should be false.

Just match any character between I and one
var str = "I dont have any one";
var str1 = "We dont have any one";
var str2 = "I dont have any more";
var str3 = "I dont have any two";
var regx = /^I.*(one|two)/
console.log(regx.test(str)) // True
console.log(regx.test(str1)) // False
console.log(regx.test(str2)) // False
console.log(regx.test(str3)) // True
Here a fiddle to test

different approach ...
var regx1 = /^I/; //this starts with I
var regx2 = /(one|two)/; //this match one or two
// starts with "I" AND contains "one" or "two".
var match = regx1.test(str1) && regx2.test(str1)

It would be better if you add a word boundary.
var regx = /^I.*? (?:one|two)( |\b).*$/;
DEMO

Related

Splitting sentence doesn't work if I am trying to split the last word

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.

How to cut third symbol from string and alert it without third symbol

How can i correctly cut out letter "v" and alert str without "v"
var str = "Javascript";
var cut = str.substring(2,3);
var str = "Javascript";
var cut = str.substring(0,2) + str.substring(3);
alert(cut);
You're using the right tool (String#substring). You need two substrings that you put back together, the "Ja" and the "ascript". So:
var str = "Javascript";
var cut = str.substring(0, 2) + str.substring(3);
alert(cut);
Another option would be String#replace, which will replace the first occurrence of what you give it unless you tell it to do it globally with a regex and the g flag (which we won't, because we just want to remove that one v):
var str = "Javascript";
var cut = str.replace("v", "");
alert(cut);
Just for fun, there is another way, but it's a bit silly: You can split the string into an array of single-character strings, remove the third entry from the array, and then join it back together:
var str = "Javascript";
var cut = str.split("").filter(function(_, index) {
return index != 2;
}).join("");
alert(cut);
or
var str = "Javascript";
var cut = str.split("");
cut.splice(2, 1); // Delete 1 entry at index 2
cut = cut.join("");
alert(cut);
...but again, that's a bit silly. :-)
use replace method
var str = "Javascript";
str = str.replace("v", "");
alert(str);

JavaScript get character in sting after [ and before ]

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

How can I replace a string by range?

I need to replace a string by range
Example:
string = "this is a string";//I need to replace index 0 to 3 whith another string Ex.:"that"
result = "that is a string";
but this need to be dinamically. Cant be replace a fixed word ...need be by range
I have tried
result = string.replaceAt(0, 'that');
but this replace only the first character and I want the first to third
function replaceRange(s, start, end, substitute) {
return s.substring(0, start) + substitute + s.substring(end);
}
var str = "this is a string";
var newString = replaceRange(str, 0, 4, "that"); // "that is a string"
var str = "this is a string";
var newString = str.substr(3,str.length);
var result = 'that'+newString
substr returns a part of a string, with my exemple, it starts at character 3 up to str.length to have the last character...
To replace the middle of a string, the same logic can be used...
var str = "this is a string";
var firstPart = str.substr(0,7); // "this is "
var lastPart = str.substr(8,str.length); // " string"
var result = firstPart+'another'+lastPart; // "this is another string"
I simple substring call will do here
var str = "this is a string";
var result = "that" + str.substring(4);
Check out a working jsfiddle.

How do I split a string and then match them with another string

Let's sat I have the sentence "I like cookies" and the sentence "I_like_chocolate_cookies".
How do I split the string "I like cookies" and check if the words exists in the second sentence?
Like this
var words = "I like cookies".replace(/\W/g, '|');
var sentence = "I_like_chocolate_cookies";
console.log(new RegExp(words).test(sentence));
https://tinker.io/447b7/1
Here's some sample code:
str1 = 'I like cookies'
str2 = 'I_like_chocolate_cookies'
// We convert the strings to lowercase to do a case-insensitive check. If we
// should be case sensitive, remove the toLowerCase().
str1Split = str1.toLowerCase().split(' ')
str2Lower = str2.toLowerCase()
for (var i = 0; i < str1Split.length; i++) {
if (str2Lower.indexOf(str1Split[i]) > -1) {
// word exists in second sentence
}
else {
// word doesn't exist
}
}
Hope this helps!
like this?
var x ="i like grape";
var c ="i_don't_like";
var xaar = x.split(' ');
for(i=0;i<xaar.length;i++){
if(c.indexOf(xaar[i])>-1) console.log(xaar[i]);
}
var foo = "I_like_chocolate_cookies";
var bar = "I like chocolate cookies";
foo.split('_').filter(function(elements) {
var duplicates = []
if(bar.split().indexOf(element) != -1) {
return true;
}
});

Categories