Replace with regExp in javascript - javascript

I have a problem with replace like this:
I have an array test :
test: Object
boolean: "true"
integer: "0"
values|+|0: "option_1"
values|+|1: "option_2"
and then i do parse like this:
for(var data in test){
for(var input in test[data]){
var input_aux = input.split('|+|');
if(input != ''){
$('table#'+table_id+' tbody td.'+input_aux[0]+' small').each(function(){
var text_highlighted = $(this).text().replace(new RegExp('(' + test[table][input] + ')', 'gi'), '<b>$1<\/b>');
$(this).html(text_highlighted);
}}}
what i'm trying to accomplish is to match the data from the array like option_1 that is in that table exactly option_1 and change the html of it to <b>option_1</b>.
And it's working fine my problem is like when i have the same key but different value like in the example above, it will highlight only option_2 and can't understand why, any idea?

The issue is the fact you are doing replacements even if there is no match. So you are reading the text() of all the elements and replacing it with that text. So you wipe out all of the existing html.
So check to see if there is a match before you do the replacement.
var re = new RegExp('(' + test[table][input] + ')', 'gi');
var txt = $(this).text();
if (txt.match(re)) {
var text_highlighted = txt.replace(re, '<b>$1<\/b>');
$(this).html(text_highlighted);
}
other option would be to use contains selector.

Related

Replace string between “variabletext[” and “]” with javascript

I'm trying to build an html form that generates structured JSON code from the input values. This form uses repeat fields.
I have to modify name attributes in cloned fields.
In Javascript I have a string 'menu-item[0][offers][0][price]'.
I would like to replace 'menu-item[0]' with 'menu-item[1]', as in example at http://regexr.com/3gpnt
I'm using RegExp, but is not required.
This is my experiment, but it doesn't work.
var string = 'menu-item[0][offers][price]';
var itemName = 'menu-item';
var regExp = new RegExp(itemName + '\[(.*?)\]', "");
var newString = string.replace(regExp, itemName + '[1]');
console.log(newString);
alert(newString);
Returns 'menu-item[0][offers][price]'.
Test on jsfiddle https://jsfiddle.net/lorenzodetomasi/dmnd7f9L/
Thank you.

If condition that pushes values that contain/match a string

I have a nicely functioning full calendar script. I have some filters for it, which basically have the following form:
$("input[name='event_filter_select']:checked").each(function () {
// I specified data-type attribute in HTML checkboxes to differentiate
// between risks and tags.
// Saving each type separately
if ($(this).data('type') == 'risk') {
risks.push($(this).val());
} else if ($(this).data('type') == 'tag') {
tagss.push($(this).val());
}
});
However the else if statement should check if the checked value 'tag' is contained within the result set, not be the only value of the result set (as implied by the ==).
Now I can only filter results that have the checked tag-value only. But i want to filter those, which have the tag-value amongst many others.
I figure this is to be done with match(/'tag'/) but i cannot figure out for the life of me how to put that into an if-statement.
Would be really glad if someone could lead me in the right direction.
I would simply do:
...
if ($(this).data('type') == 'risk') {
risks.push($(this).val());
} else if ($(this).data('type').test(/^tag/) {
tagss.push($(this).val());
}
...
This works if the 'tag' must be at the beginning of the string.
If the 'tag' can be everywhere in the string, you can use test(/tag/).
If your data is a string, example: tag filter1 filter2 filter3, you could use the indexOf-function (manual)
Code:
if ($(this).data('type').indexOf("risk") != -1))
//Action here.
indexOf returns -1 if the text isn't found.
You can use:
var re = new RegExp('\\b' + word + '\\b', 'i');
or if you wish to have the word hard-coded in (e.g., in the example, the word test):
var re = /\btest\b/i
Example showing the matches below:
var input = document.querySelector('input');
var div = document.querySelector('div');
var re;
var match;
input.addEventListener('keyup', function() {
match = input.value.trim();
re = new RegExp('\\b' + match + '\\b', 'i');
if($('div').data('type').match(re))
div.innerHTML = 'Matched the word: ' + '<strong>' + match + '</strong>';
else div.innerHTML = 'Did not match the word: ' + '<strong>' + match + '</strong>';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Word to match:<input></input><br>
Output:
<div data-type='tag tags test'></div>
With the above regular expression incorporated into your code, it should look something like this:
else if ($(this).data('type').match(/\btag\b/i) { //true for data-type that has `tag` in it.
tagss.push($(this).val());
}
Try with this condition.
/\btag\b/.test($(this).data('type'))

get particular strings from a text that separated by underscore

I am trying to get the particular strings from the text below :
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
From this i have to get the following strings: "LAST", "BRANCH" and "JENKIN".
I used the code below to get "JENKIN";
var result = str.substr(str.lastIndexOf("_") +1);
It will get the result "JENKIN.bin". I need only "JENKIN".
Also the input string str sometimes contains this ".bin" string.
with substring() function you can extract text you need with defining start and end position. You have already found the start position with str.lastIndexOf("_") +1 and adding end position with str.indexOf(".") to substring() function will give you the result you need.
var result = str.substring(str.lastIndexOf("_") +1,str.indexOf("."));
It depends on how predictable the pattern is. How about:
var parts = str.replace(/\..+/, '').split('_');
And then parts[0] is 001AN, parts[1] is LAST, etc
You can use String.prototype.split to split a string into an array by a given separator:
var str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin';
var parts = str.split('_');
// parts is ['001AN', 'LAST', 'BRANCH', 'HYB', '1hhhhh5', 'PBTsd', 'JENKIN.bin'];
document.body.innerText = parts[1] + ", " + parts[2] + " and " + parts[6].split('.')[0];
You could do that way:
var re = /^[^_]*_([^_]*)_([^_]*)_.*_([^.]*)\..*$/;
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var matches = re.exec(str);
console.log(matches[1]); // LAST
console.log(matches[2]); // BRANCH
console.log(matches[3]); // JENKIN
This way you can reuse your RegExp anytime you want, and it can be used in other languages too.
Try using String.prototype.match() with RegExp /([A-Z])+(?=_B|_H|\.)/g to match any number of uppercase letters followed by "_B" , "_H" or "."
var str = "001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin";
var res = str.match(/([A-Z])+(?=_B|_H|\.)/g);
console.log(res)
I don't know why you want to that, but this example would be helpful.
It will be better write what exactly you want.
str = '001AN_LAST_BRANCH_HYB_1hhhhh5_PBTsd_JENKIN.bin'
find = ['LAST', 'BRANCH', 'JENKINS']
found = []
for item in find:
if item in str:
found.append(item)
print found # ['LAST', 'BRANCH']

String manipulation using javascript

I am working on some string manipulations using javascript.I have a senario where i need to do a search in the string and remove certain words.
Here is my senario:
When i click 'Click me' it should look for the word in the input from the string variable,
and if matching found it should remove that word from the input.
Here is my sepecial senario, while removing the word from the input, it should remove the : and the integer value and comma (if available) which is there before the matching word.
In my example input is 1:first user,2:second user in the text box
i need the output as 2:second user
How can i achive this
<input id='textinput' type='text' value='1:first user,2:second user'></input>
<div class='click'>Click me</div>
$(document).ready(function () {
$(".click").click(function () {
var string = 'first user';
$('#textinput').val().replace(/string/g, '');
});
});
i have created a fiddle http://jsfiddle.net/h9D5W/
EDIT
here my variable string contains only user names i can't append id's with user names for example 1:first user, so the exact match will not be there in the string variable.
I have removed the starting digits, underscore and ending comma.
$(document).ready(function () {
$(".click").click(function () {
var string = 'first user';
var re = new RegExp('\\d:*'+string+',*',"g");
var text = $('#textinput').val().replace(re, '');;
$('#textinput').val(text);
});
});
Check the demo
http://jsfiddle.net/yKfur/1/
In your JavaScript code, string is a variable. You'd need to initiate the RegExp class to generate the pattern:
Also, please refrain from using variable name like string. It's the name of a global object.
var s = 'first user';
var x = $( '#textinput' ).val().replace(new RegExp(s, 'g'), '');
// use the new variable x as you wish
You should use RegExp, You need to initialize it with string variable.
Use
$(".click").click(function () {
var string = 'first user';
var re = new RegExp(string,"g"); //initialize RegExp
var text = $('#textinput').val().replace(re, ''); //Get replaced text
$('#textinput').val(text); //Reset its value
});
DEMO
EDIT
here i cant use 1:first user in the variable
$(".click").click(function () {
var arr = $('#textinput').val().split(','); //Here used split method to split string ',' as deliminator
$('#textinput').val(arr[arr.length - 1]);
});
DEMO
You can use a regular expression like:
var text = '1:first user,2:second user,3:third user';
var s = 'first user';
var re = new RegExp('^\\d+:' + s + ',?|,\\d+:' + s + '\\b');
text.replace(re, '') // '2:second user,3:third user'
I'm sure there's a shorter one though.
I have updated your fiddle
first, i split your string into array
var inputArr = ($('#textinput').val()).split(',');
so i can check each set of words using for loop,
for (i = 0; i < inputArr.length; i++) {
if (inputArr[i].indexOf(string) == -1) {
newStr = newStr + inputArr[i] + ',';
}
}
then i set the new value using substring to eliminate the last comma appended.
$('#textinput').val(newStr.substring(0, newStr.length - 1));

How can I find a specific string and replace based on character?

I'm trying to find a specific character, for example '?' and then remove all text behind the char until I hit a whitespace.
So that:
var string = '?What is going on here?';
Then the new string would be: 'is going on here';
I have been using this:
var mod_content = content.substring(content.indexOf(' ') + 1);
But this is not valid anymore, since the specific string also can be in the middle of a string also.
I haven't really tried anything but this. I have no idea at all how to do it.
use:
string = string.replace(/\?\S*\s+/g, '');
Update:
If want to remove the last ? too, then use
string = string.replace(/\?\S*\s*/g, '');
var firstBit = str.split("?");
var bityouWant = firstBit.substring(firstBit.indexOf(' ') + 1);

Categories

Resources