Regex : split string based on first occurrence, with occurance [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am terrible at regex. Please have pity and give me a hand.
I am trying to split a string by the first occurrence of And (case sensitive), into an array with a length of 2. I have no idea were to begin, so can someone help me?
var strArr = "Thing And other thing".split(/magic regex/);
expect(strArr).to.deep.equal(["Thing","And other thing"]);
var strArr = "Thing and other thing".split(/magic regex/);
expect(strArr).to.deep.equal(["Thing and other thing", ""]);
var strArr = "One Thing And other thing And yet another thing".split(/magic regex/);
expect(strArr).to.deep.equal(["One Thing","And other thing And yet another thing"]);
var strArr = "yep, just one thing".split(/magic regex/);
expect(strArr).to.deep.equal(["yep, just one thing", ""]);
UPDATE this is working exactly the way I need it to, but its still ugly:
parser = function(str) {
var spl;
spl = str.split(/\s(?=And )/);
if (spl.length > 1) {
spl = [spl.shift(), spl.join(" ")];
} else {
spl = [str, ''];
}
return spl;
};

There is no need for a regular expression for that. Just get the first index of "And" in the string:
var i = str.indexOf("And");
var strArr;
if (i == -1) {
strArr = [ str ];
} else {
strArr = [ str.substr(0, i), str.substr(i) ];
}

While Guffa's method works, if you end up needing to do this the regex way, the following will work (via a positive lookahead):
var str = "Thing And other thing";
var spl = str.split(/\s(?=And\s)/);
if (spl.length > 1)
spl = [spl.shift(), spl.join(" ")];
To test:
alert(JSON.stringify(spl));
jsFiddle
Updated to ensure it splits on [space]And[space]

I suggest doing a simple split then checking if the array has one or two
strArr.split("And", 2).length;

Related

How can i extract vowels in a Javascript String? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
If i have 'var' how can i get "e,o,o" out of it ?
With substring you can only get the position
var str = "Hello world!";
var res = str.substring(1, 4);
It's not entirely clear if you only want the vowels or if you want all except the vowels. Either way, a simple regular expression can get the characters you need.
let str = "Hello World";
let res = str.match(/[aeiou]/ig).join("");
console.log(res);
let res2 = str.match(/[^aeiou]/ig).join("");
console.log(res2);
Remove the .join("") part if you want an array, otherwise this gives you a string
How about:
var str = "Hello world!";
var theGoods = str.split('').filter(c => ['e', 'o'].includes(c)).join('');
Or if you wanted the 'inverse' behavior
var str = "Hello world!";
var theGoods = str.split('').filter(c => !['e', 'o'].includes(c)).join('');
You can loop the string and store those vowels in an array.
var arr = [];
for(var i = 0; i < str.length; i++){
if(str[i] == 'e' || str[i] == 'o'){
arr.push(str[i]);
}
}
console.log(arr);}
It's pretty easy to extract them, as long as you know RegEx (regular expression)
var str = "Hello world!" // The original string
var res = str.match(/[aeiou]/gi).join("") // Extracting the vowels
// If you want to get the consonants, here you go.
var res2 = str.match(/[^aeiou]/gi).join("")
// Logging them both
console.log(res)
console.log(res2)
function deletevowels(str) {
let result = str.replace(/[aeiou]/g, '')
return result
}
var text = "Hi test of Replace Javascript";
const a = deletevowels(text);
console.log(a);

Split string into even numbers forming a square [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
My objective is to split string (less than 80 characters) evenly to create a square or rectangle of strings.
var squareStr = function(str) {
}
console.log(squareStr('whatwonderfulday'));
console.log(squareStr('if life was easy god then god would not have given us brain to think'));
should output:
what
wond
erfu
lday
iflifewa
seasythe
ngodwoul
dnothave
givenusb
raintoth
ink
is this possible? I've been told I can use Math.sqrt but I'm not too sure how.
Thanks.
You can use a for loop to slice the string into the pieces and add a new line (\n) at the end of each chunk.
If you want to automatically use the square root of the string length you can do it like this:
function squareCode(string){
let squareString = "";
string = string.replace(/\s/g, '');
const splitNum = Math.floor(Math.sqrt(string.length));
for(i=0; i<= string.length; i+=splitNum){
squareString = `${squareString}${string.slice(i, i+splitNum)}\n`;
}
return squareString;
}
console.log(squareCode('whatwonderfulday'));
console.log(squareCode('if life was easy god then god would not have given us brain to think'));
console.log(squareCode('asdfasdf asdfasdfasd fasdfwe wer df gf dgdfgertqewdfsf fgdgewfwdsgewerfsd fdgdfgqefasdf'));
In the following function you'll pass in the string you want to slice as well as the number you want to slice at:
function squareCode(string, splitNum){
let squareString = "";
string = string.replace(/\s/g, '');
for(i=0; i<= string.length; i+=splitNum){
squareString = `${squareString}${string.slice(i, i+splitNum)}\n`;
}
return squareString;
}
console.log(squareCode('whatwonderfulday', 4));
console.log(squareCode('if life was easy god then god would not have given us brain to think', 8));
You could use this function. It replace all the empty spaces, then convert the string into an array and chunk it. Finally if merge every chunk and apply \n to each one.
var squareStr = function(str, chunk) {
str = str.replace(/ /g, '')
str = str.split('');
temp = []
for (i=0; i<str.length; i+=chunk)
temp.push(str.slice(i,i+chunk));
return temp.map(function(a){return a.join('')+"\n"}).join('')
}
console.log(squareStr('whatwonderfulday', 4));
console.log(squareStr('if life was easy god then god would not have given us brain to think', 8));
So many ways of doing that...
All other answers here are correct too, here's my approach, a more "readable" answer, using very basic recurses...
You have should at least tried...
I also have included a check to see if the string lenght is under 80.
var squareStr = function(str, charsPerLine) {
if (str.length > 80){
return;
}
str = str.replace(/ /g,'')
var stringSplited = str.split('');
var newString = '';
stringSplited.forEach(function(letter,index){
if (index % charsPerLine == 0 && newString.length > 0){
newString += '\n'; //IF YOU WANT TO USE IT IN THE HTML, USE '<br>' HERE
}
newString += letter;
});
console.log(newString);
return newString;
}
squareStr('whatwonderfulday', 4);
squareStr('if life was easy god then god would not have given us brain to think', 8);
Unless you're dealing with really long strings, I don't see a reason not to use replace to insert a newline every n characters:
function squareText(input) {
const inputNoSpaces = input.replace(/\s/g, '');
const partLen = Math.ceil(Math.sqrt(inputNoSpaces.length));
const replaceExpr = new RegExp(`.{1,${partLen}}`, 'g');
return inputNoSpaces.replace(replaceExpr, '$&\n');
}
const input = 'if life was easy then god would not have given us brain to think';
console.log(squareText(input));
This just calculates the line length and then creates a new RegExp that matches that many characters and uses it to replace each match with itself plus a newline.

Remove Part After Last Occurrence of a Word Pattern in a String [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I have this code:
var str = 'country/city/area'
var idx = str.lastIndexOf('country/city')
// idx = 0
And idx is always 0. Shouldn't idx be 12? My goal is to use it substr() in order to take the string 'area' out of the str.
var str = 'country/city/area'
var pattern = 'country/city/'
var idx = str.lastIndexOf(pattern) + pattern.length
var substring = str.substring(idx, str.length)
Explanation
1) Define the pattern you are searching for
2) Find the beginning of the pattern and add the length of the pattern => now you are at the end
3) Copy the part behind the pattern to the end of the string
if you want to get the last word, you can search for the last forward slash and get everything after it:
str.substr(str.lastIndexOf('/') + 1)
if you want to get everything after 'country/city/' but for example you don't know if this the first part of the string, you can use
str.substr(str.indexOf('country/city/') + 13);
it's not 100% clear from your question, what exactly you are trying to achieve though.
You're going to want to add the length of the string that you search for:
var str = 'country/city/area';
var checkStr = 'country/city';
var idx = str.lastIndexOf(checkStr);
var lastCharIndex = idx + checkStr.length;
// idx = 0
// idx = 12
note - it would be 12, not 13, because you didn't include the final "/" in your lastIndexOf parameter.
May be you can achieve your goal as follows;
var str = 'country/city/area',
newStr = str.replace("/area","");
console.log(newStr);

Regular expression for remove last n characters [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have a requirement to remove last n characters from string or remove 'page' from a particular string.
Eg:
var string = 'facebookpage';
Expected output string = 'facebook'
I would like to remove 'page' from the string.
Done it using substring.
var str = "facebookpage";
str = str.substring(0, str.length - 4);
Could you help me to find some better way to do it.
Regex for this:
//str - string;
//n - count of symbols, for return
function(str, n){
var re = new RegExp(".{" + n + "}","i");
return str.match(re);
};
EDIT:
For remove last n characters:
var re = new RegExp(".{" + n + "}$","i");
return str.replace(re, "");
UPDATE:
But use regex for this task, not good way; For example, AVG Runtime for 100000 iterations:
Str length solution = 63.34 ms
Regex solution = 172.2 ms
Use javascript replace function
var str = "facebookpage";
str = str.replace('page','');
You can use this regular expression :
(.*)\\w{4}
code :
var regex =(new RegExp("(.*)\\w{4}"))
val output = regex .exec("facebookpage")
// output is : ["facebookpage", "facebook"]
// output[1] is the Expected output which you want.
Hope this helps.

Count certain words in string javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am looking for a way to count certain words on a string.
$string = "How are you doing today? You are such a nice person!";
My goal is to count how many "are" in the $string variable.
Desire result: 2
Try this:
var count = yourString.match(/\bare\b/g);
count = count? count.length : 0; //checking if there are matches or not.
console.log(count);
var string = "are you bare footed?";
console.log(string.split(/\bare\b/).length - 1);
var str = "How are you doing today? You are such a nice person!";
var matchs;
matchs = str.match(/are/gi);
alert(matchs.length);
try this javascript match it returns match string as array format, and length method returns how many array index match.
try below.
var temp = "How are you doing today? You are such a nice person!.";
var count = countOcurrences(temp,"are");
alert(count);
function countOcurrences(str, value){
var regExp = new RegExp(value, "gi");
return str.match(regExp) ? str.match(regExp).length : 0;
}
Try this:
$string = "How are you doing today? You are such a nice person!";
var count = $string.match(/are/g);
alert(count.length);
Try this:
var string = "How are you doing today? You are such a nice person!";
var num = string.match(/are/g).length;
alert(num);
Here is Demo
You can also try something like this:
var temp = "How are you doing today? You are such a nice person!.";
var arr = [];
for(var i = 0;i< temp.split(' ').length; i++)
{
if(temp.split(' ')[i] === "are"){
arr.push(temp.split(' '));
}
}
alert(arr.length)

Categories

Resources