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

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

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"]

Replace a pattern with a value in javascript [duplicate]

This question already has an answer here:
javascript replace with submatch as array index
(1 answer)
Closed last year.
I'm new to JavaScript and I'm working on an application that have something like that in a string format
"lorem ipsum dolor {#variable#} sit amet {#variable2#}"
How to remove {# and #} and replace the word variable with value and for the second replaces the word variable2 and replaces it with value2
I really appreciate the help.
Thank you in advance
You could use the regex {#(.*?)#} to find the substrings you want to replace. Then, use a map object to get the corresponding value for the captured variable:
let str = `lorem ipsum dolor {#variable#} sit amet {#variable2#}`
let map = {
variable: "value1",
variable2: "value2",
}
let replaced = str.replace(/{#(.*?)#}/g, (m, p1) => map[p1])
console.log(replaced)
Regex demo

Regexp to match words two by two (or n by n)

I'm looking for a regexp which is able to match words n by n. Let's say n := 2, it would yield:
Lorem ipsum dolor sit amet, consectetur adipiscing elit
Lorem ipsum, ipsum dolor, dolor sit, sit amet (notice the comma here), consectetur adipiscing, adipiscing elit.
I have tried using \b for word boundaries to no avail. I am really lost trying to find a regex capable of giving me n words... /\b(\w+)\b(\w+)\b/i can't cut it, and even tried multiple combinations.
Regular expressions are not really what you need here, other than to split the input into words. The problem is that this problem involves matching overlapping substrings, which regexp is not very good at, especially the JavaScript flavor. Instead, simply break the input into words, and a quick piece of JavaScript will generate the "n-grams" (which is the correct term for your n-word groups).
const input = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
// From an array of words, generate n-grams.
function ngrams(words, n) {
const results = [];
for (let i = 0; i < words.length - n + 1; i++)
results.push(words.slice(i, i + n));
return results;
}
console.log(ngrams(input.match(/\w+./g), 2));
A word boundary \b does not consume any characters, it is a zero-width assertion, and only asserts the position between a word and non-word chars, and between start of string and a word char and between a word char and end of string.
You need to use \s+ to consume whitespaces between words, and use capturing inside a positive lookahead technique to get overlapping matches:
var n = 2;
var s = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
var re = new RegExp("(?=(\\b\\w+(?:\\s+\\w+){" + (n-1) + "}\\b))", "g");
var res = [], m;
while ((m=re.exec(s)) !== null) { // Iterating through matches
if (m.index === re.lastIndex) { // This is necessary to avoid
re.lastIndex++; // infinite loops with
} // zero-width matches
res.push(m[1]); // Collecting the results (group 1 values)
}
console.log(res);
The final pattern will be built dynamically since you need to pass a variable to the regex, thus you need a RegExp constructor notation. It will look like
/(?=(\b\w+(?:\s+\w+){1}\b))/g
And it will find all locations in the string that are followed with the following sequence:
\b - a word boundary
\w+ - 1 or more word chars
(?:\s+\w+){n} - n sequences of:
\s+ - 1 or more whitespaces
\w+ - 1 or more word chars
\b - a trailing word boundary
Not a pure regex solution, but it works and is easy to read and understand:
let input = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit';
let matches = input.match(/(\w+,? \w+)/g)
.map(str => str.replace(',', ''));
console.log(matches) // ['Lorem ipsum', 'dolor sit', 'amet consectetur', 'adipiscing elit']
Warning: Does not check for no matches (match() returns null)

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

Categories

Resources