Split content in last parantheses - javascript

In javascript, how can I split string to get content of last parantheses so
var str = "Lorem ipsum (I don't want this data) lorem ipsum (I want this data)";
becames array
["Lorem ipsum (I don't want this data) lorem ipsum "],["I want this data"]

You can use a regular expression and match :
var arr = str.match(/^(.*)\(([^\)]+)\)$/).slice(1);
This produces exactly
["Lorem ipsum (I don't want this data) lorem ipsum ", "I want this data"]
Online explanation of the regex

I always prefer approaches without regex, mainly for performance. It may not be pretty, but it works nontheless!
var str = "Lorem ipsum (I don't want this data) lorem ipsum (I want this data)";
var s = str.lastIndexOf('(');
var e = str.lastIndexOf(')');
var l = e - s;
var data = [
str.substr(0, s).trim(),
str.substr(s + 1, l - 1).trim()
];
// data = ["Lorem ipsum (I don't want this data) lorem ipsum", "I want this data"]

Related

Compare two strings and return different stretch

I have two strings like these:
var str1 = "lorem ipsum dolor sit amet";
var str2 = "ipsum dolor";
And I'm trying to compare them and get, as result, an array with everything that doesn't match this comparation and the match! One for the beggining and the other one for the ending.
E.g: In this case above, the return should be an array like this:
result[0] //should keep the begining **"lorem "** (with the blank space after word)
result[1] // should keep the ending **" sit amet"** (with the blank space before word)
result[2] // should keep the match **"ipsum dolor"**
All I got was an elegant solution posted by #Mateja Petrovic. But I can get this values separately.
Just like this:
const A = "ipsum dolor"
const B = "lorem ipsum dolor sit amet"
const diff = (diffMe, diffBy) => diffMe.split(diffBy).join('')
const C = diff(B, A)
console.log(C) // jumps over the lazy dog.
I'm really stuck! Any idea?
Thanks a lot!
const diff = (str, query) => [...str.split(query), query];
/*
1. we split the string into an array whenever query is found
2. we spread (...) the array into a new array
3. we add the query at the end of the new array
*/
var str = "lorem ipsum dolor sit amet";
var query = "ipsum dolor";
const result = diff(str, query)
console.log(result)
console.log(result[0])
console.log(result[1])
console.log(result[2])
I don't think what you are asking is logically possible. a "string" can be a single letter, which is going to get very messy. at best maybe something like this?
var str1 = "lorem ipsum dolor sit amet";
var str2 = "ipsum dolor";
var parts = str1.split(str2);
console.log(parts); // ['lorem ', ' sit amet']
You could split the target string by the search string, and append the latter to the solution.
const haystack = 'lorem ipsum dolor sit amet';
const needle = 'ipsum dolor';
const diff = (needle, haystack) =>
[...haystack.split(needle), needle]
console.log(diff(needle,haystack));
// ["lorem ", " sit amet", "ipsum dolor"]

Is there a Regex expression to match every that is not in quotations

I'm working on a Regular Expression that looks at everything except information in quotations. An example would be:
Lorem ipsum "dolor" sit amet, "consectetur" adipiscing elit.
Would change to
Lorem ipsum sit amet, adipiscing elit
I've already tried
.*(?=".*").*
and
`[^"].*[^"]
neither worked so I'd appreciate help.
Heres a way ...
var str = `Lorem ipsum "dolor" sit amet, "consectetur" adipiscing elit.`
console.log(str.replace(/\"[a-z]{1,}\"/g, ''))
I would do something in the line of this. It handles the case where the sentence starts or ends with a quotation mark.
var str = '"Lorem" ipsum "dolor" sit amet, "consectetur", adipiscing "elit."';
var regExp = /(?:^|\W)(\".+?\")(?:\W|$)/g;
var res = str.replace(regExp, " ").trim();
console.log(res);
RegExp explained:
(?:^|\W) - non capturing group of either start of the string or just a space (technically a "non word character" - could be a punctuation, a bracket, etc)
(\".+?\") - anything between " (including the quotation marks themselves)
(?:\W|$) - same as the first one, but checking for the end of a string instead
g flag - check for all occurrences of a matching pattern
Try this , non-greedy (".*?") match two quotations and as few as possible between them.
var a ='Lorem ipsum "dolor" sit amet, "consectetur" adipiscing elit.';
console.log(a.replace(/".*?"/g,''));
I hope to help you :
/[,\w]+(?![^" ]*")/g
var str = 'Lorem ipsum "dolor" sit amet, "consectetur" adipiscing elit.' ;
var res = '' ;
var patt = /[,\w]+(?![^" ]*")/g ;
while ( (arr = patt.exec(str)) != null) { res += arr[0] + ' ' ; }
console.log( res ) ;

Regex get the middle section of each word javascript

So essentially what I'm trying to do is loop through every word in a html document and replace the first letter of each word with 'A', the second - second last letter with 'b' and the last letter with 'c', completely replacing the word. I'm not sure if regular expressions are the way to go about doing this (should I instead be using for loops and checking each character?) however I'll ask anyway.
Currently I'm doing:
document.body.innerHTML = document.body.innerHTML.replace(/\b(\w)/g, 'A'); to get the first letter of each word
document.body.innerHTML = document.body.innerHTML.replace(/\w\b/g, 'c'); to get the last letter of each word
So if I had the string: Lorem ipsum dolor sit amet I can currently make it Aorec Apsuc Aoloc Aic Amec but I'd like to do Abbbc Abbbc Abbbc Abc Abbc in javascript.
Any help is much appreciated - regular expressions really confuse me.
You almost got it.
str = "Lorem ipsum dolor sit amet"
str = str
.replace(/\w/g, 'b')
.replace(/\b\w/g, 'A')
.replace(/\w\b/g, 'c')
document.write(str);
Fancier replacement rules can be handled with a callback function, e.g.
str = "Lorem ipsum dolor sit amet"
str = str.replace(/\w+/g, function(word) {
if (word === "dolor")
return word;
return 'A' + 'b'.repeat(word.length - 2) + 'c';
});
document.write(str);

How to make character count with Javascript

How to correctly make a character count with JS.
My code seems is incorrect, what i'm doign wrong?
<p class="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
var str = document.getElementsByClassName('text');
var res = str.innerHTML = str.value.length;
console.log(res);
This can work for you
var x = document.getElementById("text").innerHTML
var str = x.length;
alert("length is:" +str);
console.log(str);
<p id="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
If you look at this definition of the function it returns an array. So you either want the length of the array str.length or to iterate through the array.
getElementsByClassName() returns an array-like collection of elements. Iterate over it and fetch the value:
var str = document.getElementsByClassName('text');
[].forEach.call(str, function(el){
var res = el.value.length;
el.innerHTML = res;
console.log(res);
});
I guess you want to get the length of the content of an element. For that you should be using id selector, not class selector, there can be many elements with the same class but not with the same id. So you should give it some id like: <p id='some_id' class='text'>
Now you can get it through:
document.getElementById("some_id").innerHTML.length
To avoid any leading or trailing spaces, and to get exact length of text, you can try this:
document.getElementById("some_id").innerHTML.trim().length

Remove from String (from Array) in Javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove a word from a string
I have a simple string var mystr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit", and I have an array var lipsums = new Array("dolor","consectetur","elit"); Now, I want a simple function which will remove any same word in the string.
So, in the above example, it should remove the words "dolor", "consectetur", and "elit" and my string mystr should be "Lorem ipsum sit amet, adipiscing"
This script should be in Javascript (no jQuery). Any help would be appreciated.
Loop over the array of words to remove, removing all occurances via split/join:
for (var i = 0; i < lipsums.length; i++) {
mystr = mystr.split(lipsums[i]).join('');
}
http://jsfiddle.net/9Rgzd/
You may also want to clean up your whitespace afterwards, which you can do with a regex:
// Note: don't do this in the loop!
mystr = mystr.replace(/\s{2,}/g, ' ');
http://jsfiddle.net/9Rgzd/1/
Like this:
for(i=0; i<lipsums.length; i++) {
mystr = mystr.replace(new RegExp(lipsums[i],"g"), "");
}
Add this AFTER the loop to remove double white space's:
mystr = mystr.replace(/\s{2,}/g, ' ');

Categories

Resources