Javascript string replace not working inside loop - javascript

String replace is not working in javascript
My string = 'Get Flat 50% off on Tees Purchase above Rs. 1200';
output string = 'get-flat-50-percent-off-on-tees-purchase-above-rs.-1200';
here is my js code.
var json, xhr = new XMLHttpRequest();
xhr.open("GET","http://www.exmaple.com/api/v1.0/deal/deallimit/6/61f4279fb0cb4d4899810bef06539d06e349",true);
xhr.onload=function() {
var response=xhr.responseText;
var resultValue = JSON.parse(response);
var dealArray = resultValue['All deals'];
console.log(dealArray.length);
var i;
for (i = 0; i < dealArray.length; i++)
{
var key1 = 749;
var key2 = 29;
var orgProID = (dealArray[i]['productid']+dealArray[i]['productkey'])/key2;
var cat = dealArray[i]['categoryname'].toLowerCase();
var catReplace = cat.replace(" ","-");
var pro1 = dealArray[i]['productname'].toLowerCase();
var proReplace = pro1.replace('%','-percent');
var proReplace1 = proReplace.replace(" ","-");
console.log(catReplace+"/"+proReplace1);
if (dealArray[i]['price'] !=0) {
document.getElementById('appendDeals').innerHTML +="<tr><td class='dealName'>"+dealArray[i]['productname']+ " # Rs."+dealArray[i]['price']+"</td><td class='buyDeal'>BUY</td></tr>";
}
else{
document.getElementById('appendDeals').innerHTML +="<tr><td class='dealName'>"+dealArray[i]['productname']+"</td><td class='buyDeal'>BUY</td></tr>";
}
}
}
xhr.send(null);
But when i check in console log i found
get-upto 50-percent off on health & personal care products
all the places are not replaced by '-'
How to do this.

Your code isnt working because .replace() doesnt do the replacement globally inside the string. You need to set the g flag to make it work globally.
Follow this simple algorithm for getting the string converted as you want:
Make the whole string .toLowerCase()
.replace() the % with -percent
.replace() the space with a -, globally
Working Code Snippet:
var myString = 'Get Flat 50% off on Tees Purchase above Rs. 1200';
// apply the algorithm here:
var outputString = myString.toLowerCase().replace('%', '-percent').replace(/ /g,"-");
alert(outputString);
Readup: .replace() | MDN, .toLowerCase() | MDN

You need to use replace in a global sense e.g.
var proReplace = pro1.replace(/%/g,'-percent');
var proReplace1 = proReplace.replace(/ /g,'-');
Have a look at JavaScript Replace.

The proReplace.replace(" ","-"); only works for the first occurrence of substring. Take a look at here Replace multiple characters in one replace call

Related

I need help getting a number from a <p> element with javascript

I am new in JavaScript. I have 3 numbers with 10 digits in a <p> tag, and I would like to select and convert them to a link. I was able to get the numbers and convert them to link, but I am getting all 3 numbers at the same time as one link, it would be great if I can get some help, Thank you
Here is my code:
<p>
What 0123456789 exactly is this Worker thread module, 9876543210 and why do we need it? 9768352461 In this post, we will talk about the historical reasons concurrency is implemented in JavaScript and Node.js, the problems we might find, current solutions, and the future of parallel processing with Worker threads.
</p>
<script>
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = 'https://www.google.com/search?q='+text;
var rgx = /\d{10}/g;
var text = str.match(rgx);
var res = str.replace(rgx, '"'+text+'"');
document.querySelector("p").innerHTML = res;
}
myFunction();
</script>
You can capture certain expressions in regex. Then you can get value from that group by using $ and a group number. There's only one group so in this case there'll be $1;
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = "https://www.google.com/search?q=$1";
var rgx = /(\d{10})/g; // () wraps an expression in a group
var text = str.match(rgx);
var res = str.replace(rgx, '$1');
document.querySelector("p").innerHTML = res;
}
More about capturing groups: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges
Edit: I found even a simpler way - if you want to refer to the whole expression you don't need to create a group. To insert matched value you can use $&:
function myFunction() {
var str = document.querySelector("p").innerHTML;
var link = "https://www.google.com/search?q=$&";
var rgx = /\d{10}/g;
var text = str.match(rgx);
var res = str.replace(rgx, '$&');
document.querySelector("p").innerHTML = res;
}
str.match(rgx);
returns an array of matching strings. If you want to use only on item of the array, you can reference to the index (like text[0]) or you can i.e. loop over the array with text.forEach
or you can map over it and generate links like this:
let links = text.map((string) => { return `www.yourlink.com/${string}`})
in your replace statement use text instead of rgx
var res = str.replace(text, '"'+text+'"');
that way you only replace the instance of the matched text instead of all the rgx matches
EDIT
this should do it
function myFunction() {
var str = document.querySelector("p").innerHTML;
var rgx = /\d{10}/g;
var text = str.match(rgx);
for (i=0; i<text.length; i++) {
var link = 'https://www.google.com/search?q='+text[i];
str = str.replace(text[i], '"'+text[i]+'"');
}
document.querySelector("p").innerHTML = str;
}
myFunction();

Split sentence by space mixed up my index

I'm facing some problem while trying to send text to some spelling API.
The API return the corrections based on the words index, for example:
sentence:
"hello hoow are youu"
So the API index the words by numbers like that and return the correction based on that index:
0 1 2 3
hello hoow are youu
API Response that tell me which words to correct:
1: how
3: you
On the code I using split command to break the sentence into words array so I will be able to replace the misspelled words by their index.
string.split(" ");
My problem is that the API trim multiple spaces between words into one space, and by doing that the API words index not match my index. (I would like to preserve the spaces on the final output)
Example of the problem, sentence with 4 spaces between words:
Hello howw are youu?
0 1 2 3 4 5 6 7
hello hoow are youu
I thought about looping the words array and determine if the element is word or space and then create something new array like that:
indexed_words[0] = hello
indexed_words[0_1] = space
indexed_words[0_2] = space
indexed_words[0_3] = space
indexed_words[0_4] = space
indexed_words[0_5] = space
indexed_words[0_6] = space
indexed_words[0_7] = space
indexed_words[1] = how
indexed_words[2] = are
indexed_words[3] = you?
That way I could replace the misspelled words easily and than rebuild the sentence back with join command but the problem but the problem that I cannot use non-numeric indexes (its mixed up the order of the array)
Any idea how I can keep the formatting (spaces) but still correct the words?
Thanks
in that case you have very simple solution:L
$(document).ready(function(){
var OriginalSentence="howw are you?"
var ModifiedSentence="";
var splitstring=OriginalSentence.split(' ')
$.each(splitstring,function(i,v){
if(v!="")
{
//pass this word to your api and appedn it to sentance
ModifiedSentence+=APIRETURNVALUE//api return corrected value;
}
else{
ModifiedSentence+=v;
}
});
alert(ModifiedSentence);
});
Please review this one:
For string manipulation like this, I would highly recommend you to use Regex
Use online regex editor for faster try and error like here https://regex101.com/.
here I use /\w+/g to match every words if you want to ignore 1 or two words we can use /\w{2,}/g or something like that.
var str = "Hello howw are youu?";
var re = /\w+/g
var words = str.match(re);
console.log("Returning valus")
words.forEach(function(word, index) {
console.log(index + " -> " + word);
})
Correction
Just realize that you need to keep spacing as it is, please try this one:
I used your approach to change all to space. create array for its modified version then send to your API (I dunno that part). Then get returned data from API, reconvert it back to its original formating string.
var ori = `asdkhaskd asdkjaskdjaksjd askdjaksdjalsd a ksjdhaksjdhasd asdjkhaskdas`;
function replaceMeArr(str, match, replace) {
var s = str,
reg = match || /\s/g,
rep = replace || ` space `;
return s.replace(reg, rep).split(/\s/g);
}
function replaceMeStr(arr, match, replace) {
var a = arr.join(" "),
reg = match || /\sspace\s/g,
rep = replace || " ";
return a.replace(reg, rep);
}
console.log(`ori1: ${ori}`);
//can use it like this
var modified = replaceMeArr(ori);
console.log(`modi: ${modified.join(' ')}`);
//put it back
var original = replaceMeStr(modified);
console.log(`ori2: ${original}`);
Updated
var str = "Hello howw are youu?";
var words = str.split(" ");
// Getting an array without spaces/empty values
// send it to your API call
var requestArray = words.filter(function(word){
if (word) {
return word;
}
});
console.log("\nAPI Response that tell me which words to correct:");
console.log("6: how\n8: you");
var response = {
"1": "how",
"3": "you"
}
//As you have corrected words index, Replace those words in your "requestArray"
for (var key in response) {
requestArray[key] = response[key];
}
//now we have array of non-empty & correct spelled words. we need to put back empty (space's) value back in between this array
var count = 0;
words.forEach(function(word, index){
if (word) {
words[index] = requestArray[count];
count++;
}
})
console.log(words);
Correct me, if i was wrong.
Hope this helps :)
Try this JSFiddle
, Happy coding :)
//
// ReplaceMisspelledWords
//
// Created by Hilal Baig on 21/11/16.
// Copyright © 2016 Baigapps. All rights reserved.
//
var preservedArray = new Array();
var splitArray = new Array();
/*Word Object to preserve my misspeled words indexes*/
function preservedObject(pIndex, nIndex, title) {
this.originalIndex = pIndex;
this.apiIndex = nIndex;
this.title = title;
}
/*Preserving misspeled words indexes in preservedArray*/
function savePreserveIndexes(str) {
splitArray = str.split(" ");
//console.log(splitArray);
var x = 0;
for (var i = 0; i < splitArray.length; i++) {
if (splitArray[i].length > 0) {
var word = new preservedObject(i, x, splitArray[i]);
preservedArray.push(word);
x++;
}
}
};
function replaceMisspelled(resp) {
for (var key in resp) {
for (var i = 0; i < preservedArray.length; i++) {
wObj = preservedArray[i];
if (wObj.apiIndex == key) {
wObj.title = resp[key];
splitArray[wObj.originalIndex] = resp[key];
}
}
}
//console.log(preservedArray);
return correctedSentence = splitArray.join(" ");
}
/*Your input string to be corrected*/
str = "Hello howw are youu";
console.log(str);
savePreserveIndexes(str);
/*API Response in json of corrected words*/
var apiResponse = '{"1":"how","3":"you" }';
resp = JSON.parse(apiResponse);
//console.log(resp);
/*Replace misspelled words by corrected*/
console.log(replaceMisspelled(resp)); //Your solution

Split the date! (It's a string actually)

I want to split this kind of String :
"14:30 - 19:30" or "14:30-19:30"
inside a javascript array like ["14:30", "19:30"]
so I have my variable
var stringa = "14:30 - 19:30";
var stringes = [];
Should i do it with regular expressions? I think I need an help
You can just use str.split :
var stringa = "14:30 - 19:30";
var res = str.split("-");
If you know that the only '-' present will be the delimiter, you can start by splitting on that:
let parts = input.split('-');
If you need to get rid of whitespace surrounding that, you should trim each part:
parts = parts.map(function (it) { return it.trim(); });
To validate those parts, you can use a regex:
parts = parts.filter(function (it) { return /^\d\d:\d\d$/.test(it); });
Combined:
var input = "14:30 - 19:30";
var parts = input.split('-').map(function(it) {
return it.trim();
}).filter(function(it) {
return /^\d\d:\d\d$/.test(it);
});
document.getElementById('results').textContent = JSON.stringify(parts);
<pre id="results"></pre>
Try this :
var stringa = "14:30 - 19:30";
var stringes = stringa.split("-"); // string is "14:30-19:30" this style
or
var stringes = stringa.split(" - "); // if string is "14:30 - 19:30"; style so it includes the spaces also around '-' character.
The split function breaks the strings in sub-strings based on the location of the substring you enter inside it "-"
. the first one splits it based on location of "-" and second one includes the spaces also " - ".
*also it looks more like 24 hour clock time format than data as you mentioned in your question.
var stringa = '14:30 - 19:30';
var stringes = stringa.split("-");
.split is probably the best way to go, though you will want to prep the string first. I would go with str.replace(/\s*-\s*/g, '-').split('-'). to demonstrate:
var str = "14:30 - 19:30"
var str2 = "14:30-19:30"
console.log(str.replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
console.log(str2 .replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
Don't forget that you can pass a RegExp into str.split
'14:30 - 19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]
'14:30-19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]

Search through an entire string

How would you search through an entire string and display each item found in a div?
The thing I'm searching for is a license code which starts with NVOS and ends with ". I'd like to extract the entire code except for the "
The thing I want to parse would be like NVOS-ABCD-EFG-HIJK-LM52P" but I don't want the " included.
Here is what I'm trying:
var myRe = /^NVOS[^"]*/g;
var myArray = myRe.exec(document.getElementById("txt").value);
console.log(myArray)
for (i in myArray){
console.log(i)
}
Not working.
Use a regular expression.
var myString = document.body.innerHTML // substitute for your string
var regex = /NVOS[A-Z\-]+/g // /g (global) modifier searches for all matches
var matches = myString.match(regex);
for (var i=0; i<matches.length; i++)
console.log( matches[i] )
// NVOS-ABCD-EFG-HIJK-LM
// NVOS-ABCD-EFG-HIJK-LM
lests say that your string is str.
//check if the code even have this characters /x22 is for = " //
var newString = str.substr(str.indexOf("NVOS"),str.lastIndexOf("\x22") -1);
If you want to display each section in the console, then you could do it like this:
var licenseString = "NVOS-ABCD-EFG-HIJK-LM52P";
var stringSplit = licenseString.split("-");
for(var part in stringSplit) {
console.log(stringSplit[part]);
}

Javascript regex pattern array with loop

I have attempted to create a function that will replace multiple regular expression values from an array. This works if the array does not contain quotation marks of any kind, this is problematic when I want to use a comma in my pattern. So I've been trying to find an alternative way of serving the pattern with no luck. Any ideas?
function removeCharacters(str){
//ucpa = unwanted character pattern array
//var ucpa = [/{/g,/}/g,/--/g,/---/g,/-/g,/^.\s/];
var ucpa = ["/{/","/}/","/--/","/---/","/-/","/^.\s/","/^,\s/"];
for (var i = 0; i < ucpa.length; i++){
//does not work
var pattern = new RegExp(ucpa[i],"g");
var str = str.replace(pattern, " ");
}
return str;
}
WORKING:
function removeCharacters(str){
//ucpa = unwanted character pattern array
var ucpa = [/{/g,/}/g,/--/g,/---/g,/-/g,/^.\s/,/^,\s/];
for (var i = 0; i < ucpa.length; i++){
var str = str.replace(ucpa[i], " ");
}
return str;
}
REFINED:
function removeCharacters(str){
var pattern = /[{}]|-{1,3}|^[.,]\s/g;
str = str.replace(pattern, " ");
return str;
}
The RegExp constructor takes raw expressions, not wrapped in / characters.
Therefore, all of your regexes contain two /s each, which isn't what you want.
Instead, you should make an array of actual regex literals:
var ucpa = [ /.../g, /",\/.../g, ... ];
You can also wrap all that into a single regex:
var str = str.replace(/[{}]|-{1,3}|^[.,]\s/g, " ")
although I'm not sure if that's exactly what you want since some of your regexes are nonsensical, for example ,^\s could never match.

Categories

Resources