let string = 'My name is [~FIRSTNAME] [~LASTNAME]';
let nameArray = ['Peter', 'Parker'];
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]']
I want to replace the string with the elements of namearray so that the string becomes 'My name is Peter Parker'
Below is my approach to this problem -
patternToBeReplaced.forEach(function (match, index) {
var output = string.replace(match, nameArray[index]);
});
But this is not working as expected.
You could use Array#reduce and use the string for the next replacement.
let string = 'My name is [~FIRSTNAME] [~LASTNAME]';
let nameArray = ['Peter', 'Parker'];
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]']
string = patternToBeReplaced.reduce((s, m, i) => s.replace(m, nameArray[i]), string);
console.log(string);
You're creating a string templating system. Since you're using ECAMScript 6 syntax already, you could use the new built-in template literals.
let [FIRSTNAME, LASTNAME] = ['Peter', 'Parker'];
let string = `My name is ${FIRSTNAME} ${LASTNAME}`;
console.log(string);
This will also work more cleanly when there are multiple insertions of a given label within the string.
let [FIRSTNAME, LASTNAME] = ['Peter', 'Parker'];
let string = `My name is ${LASTNAME}... ${FIRSTNAME} ${LASTNAME}`;
console.log(string);
patternToBeReplaced.forEach(function (match, index) {
string = string.replace(match, nameArray[index]);
});
Something like that.
let str = 'My name is [~FIRSTNAME] [~LASTNAME]';
let nameArray = ['Peter', 'Parker'];
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]']
const result = patternToBeReplaced.reduce((str, placeholder, i) => {
return str.replace(placeholder, nameArray[i]);
}, str);
console.log(result);
output is a local variable, it's useless to just declaring it.
replace(String, String) would only replace the first matched pattern.
Here's my solution:
let replaceWithArrayElements = (patterns, replacements, targetString) => {
patterns.forEach((pattern, i) => targetString = targetString.replace(new RegExp(pattern, 'g')));
return targetString;
}
First solution, keeping your base code :
let string = 'My name is [~FIRSTNAME] [~LASTNAME]';
let nameArray = ['Peter', 'Parker'];
let patternToBeReplaced = ['[~FIRSTNAME]', '[~LASTNAME]'];
patternToBeReplaced
.forEach((match, i)=>{
string = string
.replace(match, nameArray[i]);
});
Using Map:
let string = 'My name is [~FIRSTNAME] [~LASTNAME]';
let replaceMap = new Map();
replaceMap.set('[~FIRSTNAME]', 'Peter');
replaceMap.set('[~LASTNAME]', 'Parker');
replaceMap.forEach((key, value)=>{
string = string.replace(key, value);
});
Using ES6 "template" strings:
/*
*Have some ways of getting the first name in "firstName"
*Have some ways of getting the last name in "lastName"
*/
let string = `My name is ${firstName} ${lastName}`;
string.match(/\[~\w+\]/g).forEach((item,index)=>{
string = string.replace(item, nameArray [index])
})
You can use the above code for you needs
Related
I have the following string:
myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
I would like to split it out into separate variables like:
name = "Joe";
email = "info#domian.com";
details = "I like Sushi";
I tried something like the below, but it didn't account for everything.
myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
splitString = myString.split(':');
myName = splitString[1];
myEmail = splitString[2];
myFood = splitString[3];
console.log('Name: ', myName);
console.log('Email: ', myEmail);
console.log('Food: ', myFood);
I'm wondering if there might be a creative way to do this in JS? Thanks.
This will turn your string into an object with key/value pairs using match() and split(). You can then access the variables using the object, like obj.name or obj.email. There may be a way to fix my regex so that the .shift() method isn't necessary, but it works nonetheless.
let myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
let keys = myString.match(/\w+:/g)
let values = myString.split(/\w+:/);
values.shift(); // remove first item which is empty
let obj = {};
keys.forEach((key, index) => {
obj[key.replace(":", "").toLowerCase()] = values[index].trim()
})
console.log(obj)
// access variables like obj.name or obj.email
Try this:
myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
splitString = myString.split(':');
myName = splitString[1].split(' ')[0];
myEmail = splitString[2].split(' ')[0];
myFood = splitString[3]
console.log(myName);
console.log(myEmail);
console.log(myFood);
If you want to get rid of the space in front of "I like Sushi":
details = splitString[3].split(' ');
myDetails = details[1] +' '+ details[2] +' '+ details[3]; console.log(myDetails);
var myString = "Name:Joe Email:info#domian.com Details: I like Sushi";
var arr = myString.replace(/:\s/g, ':').split(" "),
obj = {};
// .replace(/:\s/g,':') Or .replace(/[:\s]/g,':') whichever works better
for (var i = 0; i < arr.length; i++) {
var item = arr[i],
arr2 = item.split(":"),
key = arr2[0].toLowerCase();
obj[key] = arr2[1];
}
console.log(obj["email"]);
//info#domain.com
console.log(obj["details"]);
//I like Sushi
I have variables here firstName which is Faisal and lastName which is Iraqi.
let str = "Faisal Iraqi";
let [firstName, lastName] = str.split(" ");
console.log(firstName, lastName);
console.log(str.split(" "));
so I should add this properties to my new object using destructuring:
let obj = {};
obj must return firstName: "Faisal", lastName: "Iraqi"
Simply add them to the object:
let obj = {firstName, lastName};
So the whole code looks like:
let str = "Faisal Iraqi";
let [firstName, lastName] = str.split(" ");
let obj = {firstName, lastName};
console.log(obj);
Instead of using a destructuring assignment as you create new variables, you can directly destructure into the object properties:
let str = "Faisal Iraqi";
let obj = {};
[obj.firstName, obj.lastName] = str.split(" ");
console.log(obj);
How to include Parentheses () in the string when using Template literals?
Currently its output:
Test Yes Test
I expect to output like this with the parentheses:
Test (Yes) Test
Code:
let type = "Yes";
let string = `Test ${type? (type) : ''} Test`;
console.log(string);
You can use template in the template
const type = 'yes';
const string = `Test ${type? `(${type})` : ``} Test`;
console.log(string)
You need to specify that the parenthesis are part of the string and not just order of operations.
let string = `Test ${type? "(" + type + ")" : ''} Test`;
You can wrap the entire placeholder:
let type = 'yes';
let string = `Test (${type? type : ''}) Test`;
console.log(string)
Or if you need to not include it if type is falsy then you can concat them with + or use a nested placeholder:
let type = 'Yes';
let string = `Test ${type ? `(${type})` : ''} Test`;
console.log(string)
And just for fun you can write a Tagged template to make it more reusable:
function myTag(strings, ...values) {
let result = '';
strings.forEach((string, i) => {
// strings will always be +1 length over values as per the spec
const value = values[i] ? `(${values[i]})` : ''
result += string + value;
});
return result;
}
const test1 = "Yes";
const result1 = myTag`Test ${test1} Test`;
console.log(result1);
const test2 = null;
const result2 = myTag`Test ${test2} Test`;
console.log(result2);
I am trying to take an array and return a new array containing only those whose surname is 'Smith'.
I am attempting to .filter this and have been trying for quite a while but am completely out of ideas.
Please take a look at my code below, I know I am miles off, and let me kno where I might get better results? Thanks guys!
const smiths = arr.filter(function(smith) {
let nameSplit = smith.split(' ')
return nameSplit === "Smith"
});
return smiths;
Example:
arr = ['Penelope Smith', 'Charlotte Smither'] returns ['Penelope Smith']
#slouisa you almost had it, you were just missing the index for the split array.
const lastNameToFilter = "smith";
const smiths = arr.
arr = ['Penelope Smith', 'Charlotte Smither'];
const lastNameToFilter = "Smith".toLowerCase();
const smiths = arr.filter(function(fullname) {
let nameSplit = fullname.split(' ');
let lastNameIndex = 1;
return nameSplit[lastNameIndex].toLowerCase() === lastNameToFilter;
});
console.log(smiths);
filter(function(smith) {
let nameSplit = smith.split(' ');
let lastNameIndex= 1;
return nameSplit[lastNameIndex].toLowerCase() === lastNameToFilter;
});
return smiths;
You can do something like this using localeCompare to take care of case sensitivity etc:
var arr = ['Penelope Smith', 'Charlotte Smither', 'John smith']
const smiths = (a, s) => a.filter(x => x.split(' ')[1]
.localeCompare(s, 'en', {sensitivity: 'base'})==0)
console.log(smiths(arr, 'Smith'))
Another approach you could take is via endsWith and toLowerCase:
var arr = ['Penelope Smith', 'Charlotte Smither', 'John smith', 'Mark DeSmith']
const smiths = (a,s) => a.filter(x =>
x.toLowerCase().endsWith(` ${s.toLowerCase()}`))
console.log(smiths(arr, 'Smith'))
Note that endsWith does not have support in IE
I have a link like this:
https://example.com/category?variable1=value1&variable2=value2
and I need to extract page category and variable names and save it into variable and into array of variable names:
category = "category";
array = ["variable1", "variable2"];
Any sugestions how can I achieve it using Javascript?
If your link is a string like the one you reported a simple solution can be based on:
str.split([separator[, limit]]) where as separator you can use a regex
array.splice(start, deleteCount) in order to remove the first and last ele
The example:
var str = 'https://example.com/category?variable1=value1&variable2=value2';
var res = str.substr(str.lastIndexOf('/') + 1).split(/[?]|=[^&]*&{0,1}/);
var category = res[0];
var arr = res.splice(1, res.length - 2);
console.log(category);
console.log(arr);
If an object works for you as well here is a solution:
//Get variables into an object
function uriToJson (url) {
const regx = /(\?|&)([^=]+)=([^&]+)/g;
const index = url.search(regx) + 1;
const params = url.substring(index);
return JSON.parse(`{"${decodeURI(params)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"')}"}`);
}
const url = 'https://example.com/category?variable1=value1&variable2=value2'; //window.location.href...
const obj = uriToJson(url);
console.log(obj);
//Get category into a variable
var stepone = url.substring(0,url.indexOf('?'));
var steptwo = stepone.substring(stepone.indexOf('m/') + 1 )
var category = steptwo.replace('/','');
console.log(category);