Javascript search replace string from array - javascript

I am new in javascript. I want to replace string value from array if array key value match with string value
Here is my following code:
var arr= [];
arr[11] = 'XYZ';
arr[12] = 'ABC';
var string = "11-12";
My Output will be :
var str ="XYZ-ABC";

Use String#replace method with a callback.
var arr = [];
arr[11] = 'XYZ';
arr[12] = 'ABC';
var string = "11 - 12";
// match all digits in string and replace it with
// corresponding value in `arr`
var res = string.replace(/\d+/g, function(m) {
return arr[m];
})
console.log(res);

You can use regx.test() to get the Boolean value to check if it is character or not .
var arr = [];
arr[11] = 'XYZ';
arr[12] = 'ABC';
if(/[a-zA-Z\s]+/.test(arr[11])&&/[a-zA-Z\s]+/.test(arr[12])){
var str=arr[11]+ " " +arr[12];
}

You just need array methods (split map and join), neither regex nor jquery:
var str = string.split("-").map(elem => arr[elem]).join("-");

Related

How to extract specific words from a string with some patterns?

I am trying to extract some strings from a word with some pattern like -
"38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"
how will I extract all word between - separately, means first word before - and then second word between - and - and so on...
string = "38384-1-page1-2222";
string.substr(0, string.indexof("-")); //return 38384
But how will I extract 1, page1 and 2222 all the words separately?
The javascript function str.split(separator) split the string by the given separator and it returns an array of all the splited string. REF Here
Here is an example following your question :
var string = "38384-1-page1-2222";
var separator = "-";
var separated = string.split(separator);
var firstString = separated[0]; // will be '38384'
var secondString = separated[1]; // will be '1'
var thirdString = separated[2]; // will be 'page1'
/* And So on ... */
Hope this can help
Use String.prototype.split() to get your string into array
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var resultArray = [];
for (let i = 0; i < words.length;i++) {
let temp = words[i];
resultArray = pushArray(temp.split("-"), resultArray)
}
console.log(resultArray)
function pushArray (inputArray, output) {
for (let i = 0; i < inputArray.length;i++) {
output.push(inputArray[i]);
}
return output;
}
Or simply use Array.prototype.reduce()
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var result = words.reduce((previousValue, currentValue) => previousValue.concat(currentValue.split("-")), [])
console.log(result)
You can use regex /[^-]+/g
const words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
console.log(words.map(v=>v.match(/[^-]+/g)).flat())

How to split a string into an array at a given character (Javascript)

var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
//Finished result should be:
result == ["10000.", "9409.", "13924.", "11025.", "10000.", "_.", "11025.", "13225.", "_.", "9801.", "12321.", "12321.", "11664."]
After each "." I want to split it and push it into an array.
You split it, and map over. With every iteration you add an . to the end
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let result = stringToSplit.split(".").map(el => el + ".");
console.log(result)
You could match the parts, instead of using split.
var string = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.",
result = string.match(/[^.]+\./g);
console.log(result);
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
var arr = stringToSplit.split(".").map(item => item+".");
console.log(arr);
split the string using . delimiter and then slice to remove the last empty space. Then use map to return the required array of elements
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let newData = stringToSplit.split('.');
let val = newData.slice(0, newData.length - 1).map(item => `${item}.`)
console.log(val)
you could use a lookbehind with .split
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let out = stringToSplit.split(/(?<=\.)/);
console.log(out)

Json from string using regular expression

I have a string like:
const stringVar = ":20:9077f1722efa3632 :12:700 :77E: :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
I want to create JSON from above stringVar:
{
":21:" : "9077f1722efa3632",
":12:" : "700",
":27A:": "2/2",
":21A:": "9077f1722efa3632",
":27:" : "1/2",
":40A:": "IRREVOCABLE"
}
So, I was thinking I could split with regular expression (":(any Of char/digit):")
I would make the first part the key and the second part its value.
The regular expression /(:\w+:)(\S+)/ matches the whole key:value pair. You can add the g modifier, and then use it in a loop to get all the matches and put them into the object.
const stringVar = ":20:9077f1722efa3632 :12:700 :77E: :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
var regexp = /(:\w+:)(\S+)/g;
var obj = {};
var match;
while (match = regexp.exec(stringVar)) {
obj[match[1]] = match[2];
}
console.log(obj);
If you want to create an array of {key: ":20:", value: "9077f1722efa3632"}, you can modify the code to:
const stringVar = ":20:9077f1722efa3632 :12:700 :77E: :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
var regexp = /(:\w+:)(\S+)/g;
var array = [];
var match;
while (match = regexp.exec(stringVar)) {
array.push({key: match[1], value: match[2]});
}
console.log(array);
If the values can contain space, change the regexp to:
/(:\w+:)([^:]+)\s/g
This will match anything not containing : as the value, but not include the last space.
You can achieve the same result without using regex.
const stringVar = ":20:9077f1722efa3632 :12:700 :77E:xxx :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE";
const result = stringVar
.split(' ')
.reduce((ret, current) => {
const pos = current.indexOf(':', 1);
ret[current.substring(0, pos + 1)] = current.substring(pos + 1);
return ret;
}, {});
console.log(result);

Spliting a string between "," JavaScript

This is my original string,
required:true,validType:'timegt['#timeofdaymeterslotonebegintime,#timeofdaymeterslotoneendtime']
I want to split into two. the output will be like
required:true
validType:'timegt['#timeofdaymeterslotonebegintime,#timeofdaymeterslotoneendtime']
Can someone help me out with this.
first solution you split the string to obtain the two values in an Array :
var str = "required:true,validType:'timegt['#timeofdaymeterslotonebegintime,#timeofdaymeterslotoneendtime']";
var arr = str.split(",");
var result = [];
result.push(arr[0]);
result.push(arr.filter((element, index) => (index>0)).join());
console.log(result);
second solution you extract from the initial string two strings containing your values :
var str = "required:true,validType:'timegt['#timeofdaymeterslotonebegintime,#timeofdaymeterslotoneendtime']";
var index = str.indexOf(",");
var result1 = str.slice(0, index);
var result2 = str.slice(index+1);
console.log(result1);
console.log(result2);

Replace last comma separated value by another using regex

I have a string as follows :
var str = "a,b,c,a,e,f";
What I need is replace the last comma separated element by another.
ie, str = "a,b,c,a,e,anystring";
I have done it using split method and adding it to make a new string. But it is not working as expected
What I done as follows :
var str = "a,b,c,d,e,f";
var arr = str.split(',');
var res = str.replace(arr[5], "z");
alert(res);
Is there any regex to help?
You can use replace() with regex /,[^,]+$/ to match the last string
var str = "a,b,c,d,e,old";
var res = str.replace(/,[^,]+$/, ",new");
// or you can just use
// var res = str.replace(/[^,]+$/, "new");
document.write(res);
Or you can just use regex str.replace(/[^,]+$/, "new");
var str = "a,b,c,d,e,old";
var res = str.replace(/[^,]+$/, "new");
document.write(res);
Or using split() , replace the last array value with new string and then join it again using join() method
var str = "a,b,c,d,e,old";
var arr = str.split(',');
arr[arr.length - 1] = 'new';
var res = arr.join(',');
document.write(res);
You could just use a String.substring() of String.lastIndexOf():
function replaceStartingAtLastComma(str, rep){
return str.substring(0, (str.lastIndexOf(',')+1))+rep;
}
console.log(replaceStartingAtLastComma('a,b,c,d,e,f', 'Now this is f'));

Categories

Resources