Replace multiple occurence string using array element - javascript

I have several strings in an associative array:
var arr = {
'============================================': '---------',
'++++++++++++++++++++++++++++++++++++++++++++': '---------',
'--------------------------------------------': '---------'
};
I want to replace occurrences of each key with the corresponding value. What I've come up with is:
for (var i in arr)
{
strX = str.replace(i, arr[i]);
console.log('arr[\''+i+'\'] is ' + arr[i] + ': ' + strX);
}
This works, but only on first occurence. If I change the regex to /i/g, the code doesn't work.
for (var i in arr)
{
strX = str.replace(/i/g, arr[i]);
console.log('arr[\''+i+'\'] is ' + arr[i] + ': ' + strX);
}
Do you guys know how to work around this?

Instead of
strX = str.replace(/i/g, arr[i]);
you want to do something like.
strX = str.replace(new RegExp(i, "g"), arr[i]);
This is because /i/g refers to the letter i, not the value of variable i. HOWEVER one of your base string has plus signs, which is a metacharacter in regexes. These have to be escaped. The quickest hack is as follows:
new RegExp(i.replace(/\+/g, "\\+"), "g"), arr[i]);
Here is a working example: http://jsfiddle.net/mFj2f/
In general, though, one should check for all the metacharacters, I think.

The i in the regex will be the string i, not the variable i. Try instead new RegExp(i,'g'); and you should get the desired results

var W,H,A,K;
W='123456'.split(''),
H='test this WHAK com www for'.split(' '),
A='2 is a 1 (1ed 6 3 2, 1 6 3 that), 1ing 6 5.3.4';
K=0;for(K in W)A=A.split(W[K]).join(H[K]);
document.write(A);

Related

Change data inside string with box brackets

I have a string
garments[0][1]; // The 0 and 1 can be other numbers
I need to replace the data inside the second and the third box brackets.
[0] and [1]
So that it can be
garments[4][6]
Please let me know your suggestions when you get a chance, thank you.
You can try that:
var string = 'garments[' + 4 + '][' + 6 + ']'; //in your onClick function
//To increment dynamically:
var string = 'garments[' + i + '][' + j + ']'; //i and j being variables incrementing in your loops/treatments
Update to address comments:
If you want to break "garnments[0][1]" into "garnments",0 and 1 you can do the following:
var string = "garnments[0][1]";
string = string.split('['); //string = [["garnments"],["0]"],["1]"]]
string[1].replace(']','');
string[2].replace(']',''); //string = [["garnments"],["0"],["1"]]
You can then change values and rebuild your string for further use.
It is a bit brutal though. You can use RegExp as showed by #Diego
You can use String.prototype.replace()
'garments[0][1]'.replace('[0]','[4]').replace('[1]','[6]')
For any possible string with ***[m][n] format:
Function SetNewValues(testString, n, m)
{
var keyWordLengh = testString.indexOf("[");
return testString.substring(0,keyWordLengh) + "[" + n.toString() + "][" + m.toString() + "]";
}
Where:
testString is entire string to work on, like "something[342][345]"
n,m are values to be put inside brackets :)
This would be my approach.
var string = "['foobar'][2][12]";
var match =
/\[([^\]]+)\](?:\[(\d+)\])(?:\[(\d+)\])/g
.exec(string);
console.log(match);

Script running into an infinite loop while trying to insert a character

I am trying to replace all the occurrences of this symbol ' (Single inverted comma) with \' (A slash and an inverted comma).
I want to ignore the first and the last inverted comma.
To put it in an another way, I am simply trying to insert a slash before the '
Sample input: 'hello's world's'
Expected output: 'hello\'s world\'s'
I have written the following code but it seems to run into an infinite loop when I execute it.
What am I doing wrong?
And is there a more efficient way of getting it done?
text = "'hello's world's'";
for(i=text.indexOf("'") ; i<text.lastIndexOf("'");i++ )
{
if(text[i]=="'")
{
text=text.substr(0,i)+ "\\" + text.substr(i);
}
}
Here i am trying to check for the charecter if it is "'" then just adding "\" infront of it .I have taken a newarray for the result.
Each time i would slice the array,intially from 0 to index of ''' and add "//" to this sliced string,next slicing index increases from previous index of"'"+1 to current index of "'" ,this continues till the length of the string
var text = "'hello's world's'";
var delimeter = "\\";
var result = "";
var newindex = 0;
for (var i = 0; i < text.length; i++) {
if (text[i] == "'") {
var str = text.slice(newindex, i);
result += "\\" + str;
newindex = i + 1;
}
}
console.log(result);
Hope it helps
Normally you can do that with replace() function:
text.replace(/'/g,"\\'");
however since you want to ignore the first and the last inverted comma, try the following code:
text = "'hello's world's'";
first = text.indexOf("'");
last = text.lastIndexOf("'");
for (i=0; i < text.length - 1; i++)
{
if (text[i] == "'" && i != first && i != last)
{
text = text.substr(0,i) + "\\" + text.substr(i);
i++;
}
}
Two problems...
First, you're starting at the index of the first quote, which you claim you want to skip. So instead of starting with:
i=text.indexOf("'")
start with:
i=text.indexOf("'") + 1
Second, and more to the point of the infinite loop, every time you add a character the last index of the last quote increases by 1. So you're forever adding slashes to the first quote and pushing the last quote further away.
So after the first loop it's:
"'hello\'s world's'"
then:
"'hello\\'s world's'"
then:
"'hello\\\'s world's'"
And so on, infinitely.
To address this, simply increment i again any time you encounter a match:
text=text.substr(0,i)+ "\\" + text.substr(i);
i++;
The idea here is that because you've modified the string, you need to further modify your placeholder in the string (i) to compensate.
Regex help a lot in this case.
text = "'hello's world's'";
newText = text.replace(/(?!^)'(.*?)(?!$)/g,"\\'");
console.log(newText);
Here's regex tester - https://regex101.com/r/9BXvYR/1
The regex excludes first and last matches of ' and includes every ' in between
And here's the plunker - https://plnkr.co/edit/eTqQ3fK9ELFyRNexGtJI?p=preview

How to remove the extra spaces in a string?

What function will turn this contains spaces into this contains spaces using javascript?
I've tried the following, using similar SO questions, but could not get this to work.
var string = " this contains spaces ";
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
newString = string.replace(/ +/g,''); //"thiscontainsspaces"
Is there a simple pure javascript way to accomplish this?
You're close.
Remember that replace replaces the found text with the second argument. So:
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
Finds any number of sequential spaces and removes them. Try replacing them with a single space instead!
newString = string.replace(/\s+/g,' ').trim();
string.replace(/\s+/g, ' ').trim()
Try this one, this will replace 2 or 2+ white spaces from string.
const string = " this contains spaces ";
string.replace(/\s{2,}/g, ' ').trim()
Output
this contains spaces
I figured out one way, but am curious if there is a better way...
string.replace(/\s+/g,' ').trim()
I got the same problem and I fixed like this
Text = Text.replace(/ {1,}/g," ");
Text = Text.trim();
I think images always explain it's good, basically what you see that the regex \s meaning in regex is whitespace. the + says it's can be multiply times. /g symbol that it's looks globally (replace by default looks for the first occur without the /g added). and the trim will remove the last and first whitespaces if exists.
Finally, To remove extra whitespaces you will need this code:
newString = string.replace(/\s+/g,' ').trim();
We can use the below approach to remove extra space in a sentence/word.
sentence.split(' ').filter(word => word).join(' ')
Raw Javascript Solution:
var str = ' k g alok deshwal';
function removeMoreThanOneSpace() {
String.prototype.removeSpaceByLength=function(index, length) {
console.log("in remove", this.substr(0, index));
return this.substr(0, index) + this.substr(length);
}
for(let i = 0; i < str.length-1; i++) {
if(str[i] === " " && str[i+1] === " ") {
str = str.removeSpaceByLength(i, i+1);
i = i-1;
}
}
return str;
}
console.log(removeMoreThanOneSpace(str));
var s=" i am a student "
var r='';
console.log(s);
var i,j;
j=0;
for(k=0; s[k]!=undefined; k++);// to calculate the length of a string
for(i=0;i<k;i++){
if(s[i]!==' '){
for(;s[i]!==' ';i++){
r+=s[i];
}
r+=' ';
}
}
console.log(r);
// Here my solution
const trimString = value => {
const allStringElementsToArray = value.split('');
// transform "abcd efgh" to ['a', 'b', 'c', 'd',' ','e', 'f','g','h']
const allElementsSanitized = allStringElementsToArray.map(e => e.trim());
// Remove all blank spaces from array
const finalValue = allElementsSanitized.join('');
// Transform the sanitized array ['a','b','c','d','e','f','g','h'] to 'abcdefgh'
return finalValue;
}
I have tried regex to solve this problem :
let temp=text.replace(/\s{2,}/g, ' ').trim()
console.log(temp);
input="Plese complete your work on Time"
output="Please complete your work on Time"
//This code remove extra spaces with out using "string objectives"
s=" This Is Working On Functions "
console.log(s)
final="";
res='';
function result(s) {
for(var i=0;i<s.length;i++)
{
if(!(final==""&&s[i]==" ")&&!(s[i]===" "&& s[i+1] ===" ")){
final+=s[i];
}
}
console.log(final);
}
result(s);

get detailed substring

i have a problem i'm trying to solve, i have a javascript string (yes this is the string i have)
<div class="stories-title" onclick="fun(4,'this is test'); navigate(1)
What i want to achieve are the following points:
1) cut characters from start until the first ' character (cut the ' too)
2) cut characters from second ' character until the end of the string
3) put what's remaining in a variable
For example, the result of this example would be the string "this is test"
I would be very grateful if anyone have a solution.. Especially a simple one so i can understand it.
Thanks all in advance
You can use split() function:
var mystr = str.split("'")[1];
var newstr = str.replace(/[^']+'([^']+).*/,'$1');
No need to cut anything, you just want to match the string between the first ' and the second ' - see similar questions like Javascript RegExp to find all occurences of a a quoted word in an array
var string = "<div class=\"stories-title\" onclick=\"fun(4,'this is test'); navigate(1)";
var m = string.match(/'(.+?)'/);
if (m)
return m[1]; // the matching group
You can use regular expressions
/\'(.+)\'/
http://rubular.com/r/RcVmejJOmU
http://www.regular-expressions.info/javascript.html
If you want to do the work yourself:
var str = "<div class=\"stories-title\" onclick=\"fun(4,'this is test'); navigate(1)";
var newstr = "";
for (var i = 0; i < str.length; i++) {
if (str[i] == '\'') {
while (str[++i] != '\'') {
newstr += str[i];
}
break;
}
}

Javascript Split String on First Space

I have the following code as part of a table sorting script. As it is now, it allows names in the "FIRST LAST" format to be sorted on LAST name by "reformatting" to "LAST, FIRST".
var FullName = fdTableSort.sortText;
function FullNamePrepareData(td, innerText) {
var a = td.getElementsByTagName('A')[0].innerHTML;
var s = innerText.split(' ');
var r = '';
for (var i = s.length; i > 0; i--) {
r += s[i - 1] + ', ';
}
return r;
}
It currently seems to sort on the name after the LAST space (ex. Jean-Claude Van Damme would sort on 'D').
How could I change this script to sort on the FIRST space (so Van Damme shows up in the V's)?
Thanks in advance!
Instead of the .split() and the loop you could do a replace:
return innerText.replace(/^([^\s]+)\s(.+)$/,"$2, $1");
That is, find all the characters up to the first space with ([^\s]+) and swap it with the characters after the first space (.+), inserting a comma at the same time.
You can shorten that functio a bit by the use of array methods:
function FullNamePrepareData(td, innerText) {
return innerText.split(' ').reverse().join(', ');
}
To put only the first name behind everything else, you might use
function FullNamePrepareData(td, innerText) {
var names = innerText.split(' '),
first = names.shift();
return names.join(' ')+', '+first;
}
or use a Regexp replace:
function FullNamePrepareData(td, innerText) {
return innerText.replace(/^(\S+)\s+([\S\s]+)/, "$2, $1");
}
I don't know where the sorting happens; it sounds like you just want to change the reordering output.
The simplest would be to use a regexp:
// a part without spaces, a space, and the rest
var regexp = /^([^ ]+) (.*)$/;
// swap and insert a comma
"Jean-Claude Van Damme".replace(regexp, "$2, $1"); // "Van Damme, Jean-Claude"
I think you're after this:
var words = innerText.split(' '),
firstName = words.shift(),
lastName = words.join(' ');
return lastName + ', ' + firstName;
Which would give you "Van Damme, Jean-Claude"

Categories

Resources