javascript replaces text on loop from separate strings - javascript

I made loop for, from split string and try to find some text and replace it by the result of separate string, here for example :
function replaceStr(str, find, replace) {
for (var i = 0; i < find.length; i++) {
str = str.replace(new RegExp(find[i], 'gi'), replace[i]);
}
return str;
}
var str = 'some text contain car and some house contain car, or car contain someone';
var values = "cat,dog,chicken";
splt = values.split(',');
for (i = 0; i < splt.length; i++) {
var find = ['car'];
var replace = ['' + values[i] + ''];
replaced = replaceStr(str, find, replace);
}
console.log(replaced);
//console.log(splt.length);
but the result return zeros
I want find all "car" text and replace it from splited text by comma characters
anyone can help me please..

hum what is the goal of your replaceStr function ?
maybe this is enough :
var str = 'some text contain car and some house contain car, or car contain someone';
var values = "cat,dog,chicken";
splt = values.split(',');
for (i = 0; i < splt.length; i++) {
var find = 'car';
str = str.replace(find, splt[i]);
}
console.log(str);

I guess implicitly from your question you want to replace "car" with cat, dog, chicken progressively to achieve this:
"some text contain cat and some house contain dog, or chicken contain someone"
So roughly this would be your solution:
var str = 'some text contain car and some house contain car, or car contain someone';
var values = "cat,dog,chicken";
var splt = values.split(',');
var replaced = str;
for (i = 0; i < splt.length; i++) {
replaced = replaced.replace('car', splt[i]);
}
console.log(replaced);

Related

JavaScript Regex Match Strings

I'm trying to create a small program that converts a string to a JavaScript variable. I am trying to figure out how to do this. I can't seem to figure out how to use .match...
Here is my code
function convertVariables(){
var matches = code.match(/#[^;]+/g);
for(var i = 0; i < matches.length; i++){
code = code.replace(matches[i].substring(0, 1), "var ");
console.log("Found one");
}
}
If the input would be:
#somevariable = "some string";
#anothervariable = 12;
The output should be:
var somevariable = "some string";
var anothervariable = 12;

Word count issue with JS

I am very, very new at JS with no programming experience and I am struggling with creating a script that counts words in a text box. I have the following code and I can't get anything to populate:
var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function(){
var wordsCounted = myTextareaElement.value;
var i = 0;
var str = wordsCounted;
var words = str.split('');
for (var i = words.length; i++) {if (words[i].length > 0; i++) { words[i] };
}
And for the Span Id in my HTML, I put the following:
<span id="wordsCounted"></span>
Any direction I where I am royally messing up would be great. I have tried it in JS fiddle and can't get it to populate.
The split method needs a proper character, you can use an space " " or a regex to indicate any whitespace character: "My name is XXX".split(/\s+/) will show ["My", "name", "is", "XXX"].
If you just want the number of words you can do "My name is XXX".split(/\s+/).length, which will return 4.
Try this, this may do what you want. Instead of doing a for loop, just count how many words are there and display the length of the array.
var myTextareaElement = document.getElementById("myWordsToCount");
myTextareaElement.onkeyup = function(){
var wordsCounted = myTextareaElement.value;
var i = 0;
var str = wordsCounted;
var words = str.split('');
if (words.length > 0){
document.getElementById('wordsCounted').innerHTML = words.length;
}
}

Get first word of string

Okay, here is my code with details of what I have tried to do:
var str = "Hello m|sss sss|mmm ss";
//Now I separate them by "|"
var str1 = str.split("|");
//Now I want to get the first word of every split-ed sting parts:
for (var i = 0; i < codelines.length; i++) {
//What to do here to get the first word of every spilt
}
So what should I do there? :\
What I want to get is :
firstword[0] will give "Hello"
firstword[1] will give "sss"
firstword[2] will give "mmm"
Use regular expression
var totalWords = "foo love bar very much.";
var firstWord = totalWords.replace(/ .*/,'');
$('body').append(firstWord);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Split again by a whitespace:
var firstWords = [];
for (var i=0;i<codelines.length;i++)
{
var words = codelines[i].split(" ");
firstWords.push(words[0]);
}
Or use String.prototype.substr() (probably faster):
var firstWords = [];
for (var i=0;i<codelines.length;i++)
{
var codeLine = codelines[i];
var firstWord = codeLine.substr(0, codeLine.indexOf(" "));
  firstWords.push(firstWord);
}
To get first word of string you can do this:
let myStr = "Hello World"
let firstWord = myStr.split(" ")[0]
console.log(firstWord)
split(" ") will convert your string into an array of words (substrings resulted from the division of the string using space as divider) and then you can get the first word accessing the first array element with [0].
See more about the split method.
I 'm using this :
function getFirstWord(str) {
let spaceIndex = str.indexOf(' ');
return spaceIndex === -1 ? str : str.substring(0, spaceIndex);
};
How about using underscorejs
str = "There are so many places on earth that I want to go, i just dont have time. :("
firstWord = _.first( str.split(" ") )
An improvement upon previous answers (working on multi-line or tabbed strings):
String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}
Or using search and substr:
String.prototype.firstWord = function(){let sp=this.search(/\s/);return sp<0?this:this.substr(0,sp)}
Or without regex:
String.prototype.firstWord = function(){
let sps=[this.indexOf(' '),this.indexOf('\u000A'),this.indexOf('\u0009')].
filter((e)=>e!==-1);
return sps.length? this.substr(0,Math.min(...sps)) : this;
}
Examples:
String.prototype.firstWord = function(){return this.replace(/\s.*/,'')}
console.log(`linebreak
example 1`.firstWord()); // -> linebreak
console.log('space example 2'.firstWord()); // -> singleline
console.log('tab example 3'.firstWord()); // -> tab
var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');
//Now i want to get the first word of every split-ed sting parts:
for (var i=0;i<str1.length;i++)
{
//What to do here to get the first word :)
var firstWord = str1[i].split(' ')[0];
alert(firstWord);
}
This code should get you the first word,
var str = "Hello m|sss sss|mmm ss"
//Now i separate them by "|"
var str1 = str.split('|');
//Now i want to get the first word of every split-ed sting parts:
for (var i=0;i<str1.length;i++)
{
//What to do here to get the first word :(
var words = str1[i].split(" ");
console.log(words[0]);
}
In modern JS, this is simplified, and you can write something like this:
const firstWords = str =>
str .split (/\|/) .map (s => s .split (/\s+/) [0])
const str = "Hello m|sss sss|mmm ss"
console .log (firstWords (str))
We first split the string on the | and then split each string in the resulting array on any white space, keeping only the first one.
I'm surprised this method hasn't been mentioned: "Some string".split(' ').shift()
To answer the question directly:
let firstWords = []
let str = "Hello m|sss sss|mmm ss";
const codeLines = str.split("|");
for (var i = 0; i < codeLines.length; i++) {
const first = codeLines[i].split(' ').shift()
firstWords.push(first)
}
const getFirstWord = string => {
const firstWord = [];
for (let i = 0; i < string.length; i += 1) {
if (string[i] === ' ') break;
firstWord.push(string[i]);
}
return firstWord.join('');
};
console.log(getFirstWord('Hello World'));
or simplify it:
const getFirstWord = string => {
const words = string.split(' ');
return words[0];
};
console.log(getFirstWord('Hello World'));
This code should get you the first word,
const myName = 'Jahid Bhuiyan';
console.log(myName.slice(0, myName.indexOf(' ')));
Ans will be "Jahid"

How to get unmatched keywords?

I am using this as keyword s='young girl jumping'
function selfreplace(s) {
var words = ['man', 'jumping'];
var re = new RegExp('\\b(' + words.join('|') + ')\\b', 'g');
var specials = [];
var match;
var str = "";
while(match = re.exec(s)) {
str += match[0] + '(k)';
}
return str;
}
It is returning jumping(k)
I want the result to be young(s) girl(s) jumping(k)
It would probably be easiest to check if it's in words outside of the regex:
function selfreplace(s) {
var words = ['man','jumping'];
var re = new RegExp('\\b(\\w+)\\b', 'g');
var specials = [];
var match;
var str = "";
while(match = re.exec(s))
{
if (words.indexOf(match[0]) !== -1))
str += match[0] + '(k)';
else
str += match[0] + '(s)';
}
return str;
}
You can use a replace with callback.
function selfreplace(s){
return s.replace(/man|jumping|(\w+)/g, function(word, misc){
return word + (misc? '(s)' : '(k)')
})
}
If the word matched is man or jumping, only the first argument (entire match) is set. If the word matched is any other, the first capturing group is set as well.
If you don't know the set of words ahead, you can still generate the regex on the fly. Assuming words don't contain non-word characters:
function selfreplace(s, words){ //or any other method of passing 'words'
var re = RegExp(words.join("|")+"|(\\w+)",'g');
return s.replace(re, function(word, misc){
return word + (misc? '(s)' : '(k)')
})
}
Just a different approach, probably not the best solution but thought i'd throw it out there.
var str = "young girl jumping";
function replaceStr(s){
var matched = new RegExp("man|jumping", "i");
var newStr = "";
var str = s.split(" ");
for(var i=0; i<str.length;i++){
if(str[i].match(matched)){
newStr += str[i]+"(k) ";
} else {
newStr += str[i]+"(s) ";
}
}
return newStr.substr(0, newStr.length-1);
}
//replaceStr(str) returns "young(s) girl(s) jumping(k)"
DEMO here
if the matched words might change then you can always amend this function so it accepts an array as the second argument and then creates the regexp dynamically
replaceStr(s, matchArr){} and
var matched = new RegExp("("+matchArr.join("|")+")", "i");
Something like this might give you a hint:
var s = "young girl jumping",
words = ['man','jumping'],
regex = new RegExp("(" + words.join("|") +")", "g"),
q = s.replace(regex, function( string ) {
return string + "(k)";
});
console.log(q); // "young girl jumping(k)"
If you match words only, you do not really need regexps at all, do you?
What about just looking for the words with ==
function selfreplace(s) {
var words = ['man','jumping'];
var input = s.split(" ");
var str = "";
for(var i=0; i<input.length; i++){
var tmpString = "(s)";
for(var j=0; j<words.length; j++){
if(input[i] == words[j]){
tmpString = "(k)";
}
}
str += input[i]+tmpString;
}
return str;
}
You could use a RegExp for this, but for what you are doing a RegExp is overkill. I would use Array methods instead:
var selfreplace = function selfreplace(s) {
var words = ['man', 'jumping'],
i = 0,
suffix = '(s)';
s = s.split(' ');
for (i = 0; i < s.length; i += 1) {
if (words.indexOf(s[i]) > -1) {
s[i] = s[i] + '(k)';
} else {
s[i] = s[i] + '(s)';
}
}
return s.join(' ');
};
Here's a fiddle in action: http://jsfiddle.net/4KAzw/

Count occurances in string from keyword array in javascript

I have an array:
var locations = ['Afghanistan','Albania','Algeria','New York'];
and a string:
var string = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';
I want to count the number of times each keyword in the array appears in the string but can't figure out the best way to do that.
Here is my version:
function countItems(a, s) {
var x, i, output = {};
for (x = 0; x < a.length; x++) {
i = 0;
output[a[x]] = 0;
while ((i = s.indexOf(a[x], i)) > -1) {
output[a[x]]++;
i++
}
}
return output;
}
var result = countItems(locations, string);
// result['Albania'] === 0
Try it out here.
Try something like this. You could modify what you do with count -- store it in another array, display it (which is what this script does), etc.
var locations = ['Afghanistan','Albania','Algeria','New York'];
var str = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';
for(var i=0; i<locations.length; i++) {
var pattern = new RegExp(locations[i], "g");
var m = str.match(pattern);
if (m != null)
{
var count = m.length; // the count
alert("There are " + count + " occurrences of " + locations[i]);
}
}
<script language="JavaScript">
var locations = ['Afghanistan','Albania','Algeria','New York'];
var string1 = 'I love Afghanistan New York Afghanistan Andorra Andorra Algeria New York';
for (var i=0;i<locations.length;i++) {
nCount = string1.split(locations[i]).length-1;
document.write(locations[i] + ' is found ' + nCount + ' times<br>');
}
</script>
This code only instantiates one RegExp object and uses a reverse while-loop. I'm pretty sure this is as fast as you can go without breaking the laws of physics :)
This is whats happening:
Construct regular expression string using a reverse while-loop
New up just one RegExp object, and match() it on the string
Count the length of the array returned by the match() function
Here's the implementation:
var countries = ["Afganistan", "America", "Island"];
var sentence = "I love Afganistan, America.. And I love America some more";
function countOccurrences(a, s)
{
var re = "",
l = a.length,
m;
while (l)
{
l--;
re += a[l];
if (l > 0) re += "|";
}
m = s.match(new RegExp(re, "gi")) || [];
return m.length;
}
Note: I am of course expecting the entries in the array to be sanitized for any special characters that will break the regular expression constructed within the function.
var occurrences = function countOccurrences(countries, sentence); // returns 3

Categories

Resources