Javascript replace string with list from array - javascript

I have a string that is a normal sentence. I need to replace the characters in the string if they are found in a given array. For example,
const arr = ["(model: Audi)", "(model: Kia)"];
if the string is:
"How is your (model: Audi) today?";
The result should be "How is your Audi today?".
Is there a way to do this with regex? I read somewhere that regex has better performance. I've tried looping thru the array then replacing the characters but I couldnt get it working and my solution would have nested loops due to the given string

const arr = ["(model: Audi)", "(model: Kia)"];
let string = "How is your (model: Audi) today?";
for (let data of arr){
string = string.replace(data, data.split(": ")[1].replace(")",""))
}
console.log(string);

Well, this is the simplest I have managed to do.
However, I myself kind of consider it a bad solution.
Let me know if it helps at all...
const myString = "How is your (model: Audi) today?";
const arr = ["(model: Audi)", "(model: Kia)"];
arr.forEach(item => {
const part = item.match(/\w+\)$/)[0];
const subPart = part.substring(0, part.length - 1);
if (myString.includes(item))
console.log(myString.replace(item, subPart));
});

Related

Understanding how to count the characters in a string in order to use slice() on a part of the string

I am learning JavaScript , the fundamentals for now and what I don’t get, is how to count the characters in the string in order to use the slice on the certain string and extract a certain word out of the string.
For example
let text = "JavaScript", "apples", "avocado");
let newText = text.slice(?),(?);
How do I know or count the position of apples for example or JavaScript?
Thank you!
Try like this:
let text = "JavaScript, apples, avocado";
let newText = text.slice(text.indexOf("JavaScript"));
let newText2 = text.slice(text.indexOf("apples"));
console.log(newText)
console.log(newText2)
Few observations/suggestions :
String will always wrapped with the quotes but in your post it is not looks like a string.
Why you want to slice to get the word from that string ? You can convert that string into an array and then get that word.
Implementation steps :
Split string and convert that in an array using String.split() method.
Now we can find for the word you want to search from an array using Array.find() method.
Working Demo :
// Input string
const text = "JavaScript, apples, avocado";
const searchText = 'apples';
// Split string and convert that in an array using String.split() method.
const splittedStringArray = text.split(',');
// Now we can find for the word from splittedStringArray using Array.find() method.
const result = splittedStringArray.find(item => item.trim() === searchText);
// Output
console.log(result);
split the string into an array, , and then splice in the string you do want. Finally, join the array elements into a new string.
const str = 'JavaScript, apples, avocado';
function replace(str, search, replacement) {
// Create an array using `split`
const arr = str.split(', ');
// Find the index of the item you're looking for
const index = arr.findIndex(el => el === search);
// `splice` in the new replacement string
arr.splice(index, 1, replacement);
// Return the new string
return arr.join(', ');
}
console.log(replace(str, 'apples', 'biscuit'));

Get all occurrences of value in between two patterns in JavaScript

I have to the following long string. How do I extract all the values that are in between "url=" and "," so that I then have the following array?
"load("#bazel_tools//tools/build_defs/repo:http.bzl","http_jar")definclude_java_deps():http_jar(name="com_google_inject_guice",sha256="b378ffc35e7f7125b3c5f3a461d4591ae1685e3c781392f0c854ed7b7581d6d2",url="https://repo1.maven.org/maven2/com/google/inject/guice/4.0/guice-4.0.jar",)http_jar(name="org_sonatype_sisu_inject_cglib",sha256="42e1dfb26becbf1a633f25b47e39fcc422b85e77e4c0468d9a44f885f5fa0be2",url="https://repo1.maven.org/maven2/org/sonatype/sisu/inject/cglib/2.2.1-v20090111/cglib-2.2.1-v20090111.jar",)http_jar(name="javax_inject_javax_inject",sha256="91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff",url="https://repo1.maven.org/maven2/javax/inject/javax.inject/1/javax.inject-1.jar",)"
[
https://repo1.maven.org/maven2/com/google/inject/guice/4.0/guice-4.0.jar,
https://repo1.maven.org/maven2/org/sonatype/sisu/inject/cglib/2.2.1-v20090111/cglib-2.2.1-v20090111.jar,
https://repo1.maven.org/maven2/javax/inject/javax.inject/1/javax.inject-1.jar
]
I've tried the following, but it only gives me the first occurrence of it, but I need them all. Thanks!
var arr = contents.split('url=').pop().split(',')
for(i in arr) {
console.log(arr[i]);
}
You can solve this by using a Regular Expression
const regEx = /(?:url=")([^,]+)(?:",)/gm;
const string = 'load("#bazel_tools//tools/build_defs/repo:http.bzl","http_jar")definclude_java_deps():http_jar(name="com_google_inject_guice",sha256="b378ffc35e7f7125b3c5f3a461d4591ae1685e3c781392f0c854ed7b7581d6d2",url="https://repo1.maven.org/maven2/com/google/inject/guice/4.0/guice-4.0.jar",)http_jar(name="org_sonatype_sisu_inject_cglib",sha256="42e1dfb26becbf1a633f25b47e39fcc422b85e77e4c0468d9a44f885f5fa0be2",url="https://repo1.maven.org/maven2/org/sonatype/sisu/inject/cglib/2.2.1-v20090111/cglib-2.2.1-v20090111.jar",)http_jar(name="javax_inject_javax_inject",sha256="91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff",url="https://repo1.maven.org/maven2/javax/inject/javax.inject/1/javax.inject-1.jar",)'
const matches = string.matchAll(regEx);
for (const match of matches) {
console.log(match[1]);
}
Or with string methods
const string = 'load("#bazel_tools//tools/build_defs/repo:http.bzl","http_jar")definclude_java_deps():http_jar(name="com_google_inject_guice",sha256="b378ffc35e7f7125b3c5f3a461d4591ae1685e3c781392f0c854ed7b7581d6d2",url="https://repo1.maven.org/maven2/com/google/inject/guice/4.0/guice-4.0.jar",)http_jar(name="org_sonatype_sisu_inject_cglib",sha256="42e1dfb26becbf1a633f25b47e39fcc422b85e77e4c0468d9a44f885f5fa0be2",url="https://repo1.maven.org/maven2/org/sonatype/sisu/inject/cglib/2.2.1-v20090111/cglib-2.2.1-v20090111.jar",)http_jar(name="javax_inject_javax_inject",sha256="91c77044a50c481636c32d916fd89c9118a72195390452c81065080f957de7ff",url="https://repo1.maven.org/maven2/javax/inject/javax.inject/1/javax.inject-1.jar",)'
const arr = string.split('url="');
const urls = arr
.filter((subStr) => subStr.includes('https://'))
.map((subStr) => subStr.split('",)')[0]);
console.log(urls);
The RegEx solution is of course widely more flexible.
Be aware that Regular Expressions can be "unsafe" which means they might have extremely long evaluation times depending on the input. Libraries like this can help you detect these

How can I convert each of the words in a string to each be an array?

Is there a way to convert each word of a string to each have an array? For example, say I have the variable below.
Let str = "Just typing out some words";
I would like to convert this to what I have below
Let arrs = [[Just], [typing], [out], [some], [words]]
Is there any way that I can achieve this?
const str = "Just typing out some words";
const arr = str.split(' ').map((node) => [node]);
console.log(arr);
This would do the job.
str.split(" ").map((s) => [s])

Implement search feature using Regex

I have implemented the search feature using JavaScript and Regex. Firstly, I converted the input string into tokens then searched for it in the target array.
This is the sample code.
const tokens = inputString
.toLowerCase()
.split(' ')
.filter(function (token) {
return token.trim() !== ''
})
const searchTermRegex = new RegExp(tokens.join(' '), 'gim')
const filteredList = targetArray.filter(function (item) {
return item.match(searchTermRegex)
})
This code is running fine, only problem is it does not search if the words are present in random order.
For example, if target string is "scrape the data from pages", and I search for "data scrape" then it is not able to detect it.
What's the better solution for it?
Expected Output: If at least a single word from the input is present in the target string, it should show that string in the final output.
Since it's not clear whether your need both the words in your targeted result or either of them, there is an answer for either case therefore I'm adding solution if both words are need for which you'll need positive lookaheads, and it seems like your requirement is that you need to have both word complete in your inputString, that's why I've added word boundaries in the regex using \b, if that's not needed you can update the token mapper with this:
(?=.*${token})
Also I've refactored your code a little bit, hope that helps
const tokens = inputString
.split(' ')
.filter(Boolean)
.map(token => `(?=.*\\b${token}\\b)`);
const searchTermRegex = new RegExp(tokens.join(''), 'gim');
const filteredList = targetArray.filter(item => item.match(searchTermRegex));
You could do like this. I think split not necessary
const inputString = "scrape the data from pages"
const targetArray = ["data", "scrape"]
const filteredList = targetArray.every(function(item) {
return inputString.indexOf(item) > -1
})
console.log("matchStatus", filteredList)
OR Regex
const inputString = "scrape the data from pages"
const targetArray = ["data", "scrape"]
const filteredList = new RegExp(targetArray.join('|'),'gim').test(inputString)
console.log("matchStatus", filteredList)

javascript split with regex

I would like to split characters into array using javascript with regex
foo=foobar=&foobar1=foobar2=
into
foo, foobar=,
foobar1, foobar2=
Sorry for not being clear, let me re describe the scenario.
First i would split it by "&" and want to post process it later.
str=foo=foobar=&foobar1=foobar2=
var inputvars=str.split("&")
for(i=0;i<inputvars.length;i++){
var param = inputvars[i].split("=");
console.log(param);
}
returns
[foo,foobar]
[]
[foobar1=foobar2]
[]
I tried to use .split("=") but foobar= got splited out as foobar.
I essentially want it to be
[foo,foobar=]
[foobar1,foobar2=]
Any help with using javascript to split first occurence of = only?
/^([^=]*)=(.*)/.exec('foo=foobar=&foobar1=foobar2=')
or simpler to write but using the newer "lazy" operator:
/(.*?)=(.*)/.exec('foo=foobar=&foobar1=foobar2=')
from malvolio, i got to conclusion below
var str = 'foo=foobar=&foobar1=foobar2=';
var inputvars = str.split("&");
var pattern = /^([^=]*)=(.*)/;
for (counter=0; counter<inputvars.length; counter++){
var param = pattern.exec(inputvars[counter]);
console.log(param)
}
and results (which is what i intended)
[foo,foobar=]
[foobar1,foobar2=]
Thanks to #malvolio hint of regex
Cheers

Categories